Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to extract and compress folders in batches with Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to extract and compress folders in batches of Python". In daily operation, I believe many people have doubts about how to extract and compress folders in batches of Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to extract and compress folders in batches of Python". Next, please follow the editor to study!

1. Batch decompression of python

Tip: if it is important data, please back up before decompression, after decompression will overwrite the original compressed file!

Before decompression:

After decompression: the file name is English:

The file name contains Chinese:

The code is as follows

Import osimport shutilimport zipfile # first introduces the required toolkit # shutil for later moving files, you can ignore this # path and change it here! # parent_path = r 'enter the path, which will extract all zip files under this path.' parent_path = ritual E:\ py\ python3.7\ test\ test99\ zip' # File Type selection # you can change the compressed file type by yourself, and you need to introduce other toolkits, such as tarfile. # here, because zip is more common on your own windows For other types, please change file_flag = '.zip' # modify the format to be unzipped for example: .rar # Delete the extracted zip file # it is not recommended to use it for the first time After confirming that the program is correct, you can add def del_old_zip (file_path): os.remove (file_path) # decompress def decompress (file_path, root): # start # zipfile Open the zip file z = zipfile.ZipFile (f'{file_path}','r') # decompress z.extractall (path=f "{root}") # path as the decompression path After unpacking, locate under this path # determine whether you need to unpack for names in z.namelist (): if names.endswith (file_flag): z.close () return 1 # end z.close () return 0 # because in the course of use, I found that some zip will be mixed together after unpacking. # usually everyone manually When decompressing, you may also encounter the question of whether to overwrite or not # the following two functions solve this problem # to start by creating a large folder with the same name as the compressed package # to avoid later confusion and trouble def start_dir_make (root Dirname): os.chdir (root) os.mkdir (dirname) return os.path.join (root, dirname) # remove redundant folders def rem_dir_extra (root Father_dir_name): # Recursive pay attention to the normal handling of information. Maybe the last call has changed something, but the following call still uses the previous data try: # determine whether the folder starts with the same name as for item in os.listdir (os.path.join (root, father_dir_name)): # the first step is to determine whether it is a folder If not, skip this loop if not os.path.isdir (os.path.join (root, father_dir_name, item): continue # determines whether to remove a layer of directory structure # folder name should be the same And there is only a single folder in the subdirectory if item = = father_dir_name and len (os.listdir (os.path.join (root, father_dir_name) = = 1: # change the working directory os.chdir (root) # rename the useless folder Because os.rename (father_dir_name, father_dir_name +'- old') # removes the empty folder shutil.move (root, father_dir_name +'- old', item) after moving the file directly. Os.path.join (root)) os.rmdir (os.path.join (root, father_dir_name +'- old')) # will continue to recursively process the folder after removing a layer of directory structure as a parent # note here The above data has been changed, so the following recursive parameters must be correct! Rem_dir_extra (root, item) else: # handles folders that do not meet the above criteria rem_dir_extra (os.path.join (root, father_dir_name) Item) except Exception as e: # print error message print ("error clearing folder" + str (e)) # entry if _ _ name__ = ='_ _ main__': flag = 1 while flag: # Loop through folder for root, dirs Files in os.walk (parent_path): # read file name for name in files: if name.endswith (file_flag): # create folder new_ws = start_dir_make (root, name.replace (file_flag) )) # zip file address zip_path = os.path.join (root, name) # decompress flag = decompress (zip_path New_ws) # Delete unzipped files # it's a little dangerous # but if you don't delete it, it may run repeatedly # be sure to back up or test first Otherwise, it might get cold. I choose to modify del_old_zip (zip_path) # to remove the redundant file structure rem_dir_extra (root, name.replace (file_flag,'') print (f'{root}\ {name} '.join ([' file:') '\ ndecompression completed\ n']) # because the decompression may have been unzipped several times, there may be a parent directory with the same name that cannot be processed. Here we need to process rem_dir_extra (os.path.split (parent_path) [0], os.path.split (parent_path) [1]) print ("decompression is complete. Remember to check if there is anything other than the zip format!\ n\ nThe other formats need to be changed by yourself. (2) python batch compression

Before compression:

After compression:

The code is as follows:

Import zipfileimport osdef zip_yasuo (start_dir): file_news = start_dir + '.zip' if not os.path.isfile (file_news): Z = zipfile.ZipFile (file_news, 'zip, zipfile.ZIP_DEFLATED) for dir_path, dir_names, file_names in os.walk (start_dir): file_path = dir_path.replace (start_dir) '') file_path = file_path and file_path + os.sep or 'for filename in file_names: z.write (os.path.join (dir_path, filename) File_path+filename) z.close () if _ _ name__ = "_ _ main__": base_path = r "E:\ py\ python3.7\ test\ test99\ zip" base_path_list = os.listdir (base_path) for base_path_list_one in base_path_list: base_path_list_one_dir = os.path.join (base_path) Base_path_list_one) # subdirectory print ("prepare to compress subdirectories to be compressed", base_path_list_one_dir) if os.path.isdir (base_path_list_one_dir): zip_yasuo (base_path_list_one_dir) so far The study on "how to decompress and compress folders in batches" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report