Python Operation zip file

Source: Internet
Author: User

Python Operation zip file

Need to use to ZipFile module

Read zip file

Any zip file, I use Bb.zip here, is a folder BB, there is a file aa.txt.

Import ZipFile# default mode R, read Azip= ZipFile. ZipFile (' Bb.zip ')# [' bb/', ' bb/aa.txt ']# return all folders and files print (azip.namelist ()) # # returns the zip filename # compressed files in the BB folder under Aa.txtazip_info = Azip.getinfo ( ' bb/aa.txt ')  # original file size print (azip_info.file_size) # Compressed size print (azip_info.compress_size)  # This can be obtained compression rate, reserved two digits after the decimal point print (format (azip_info.file_size/azip_info.compress_size))       

You can see that the open way is not an imagined open, but a zipfile. namelist()You can return all the folders and file paths inside. getinfoyou can get information about the file under a path, as above.

can also directly read the contents of the files in the compressed package, the following two ways to get the same result. It is important to note that the data read seems to be in the form of bytes, decoding into Utf-8 is good .

# 可以直接读取里面的内容, 不过貌似是字节形式.需要解码回utf-8.参数也可以传ZiInfo, 如ba = azip.read(‘bb/cc.txt‘).decode(‘utf-8‘)print(a)# 打开文件再读取,好像比上面麻烦b = azip.open(azip_info)print(b.read().decode(‘utf-8‘))azip.close()

Remember to close when you're done with your resources.

Unzip zip

The most critical function, a sentence to be done. The default decompression in the current working directory , you can specify the decompression directory.

azip.extractall()
New zip file

Not only can read but also write. When creating a new compressed package, you can choose a compression algorithm, such as deflated and LZMA

# Create a new compressed package, put the file in, if the compressed package already exists, will overwrite. option to use a mode, append Azip= ZipFile. ZipFile (' bb.zip ', ' W ')# must ensure that the path exists, add the BB clip (and its lower aa.txt) to the compression packet, the compression algorithm lzmaazip.write (' D:/bb/aa.txt ', Compress_type=zipfile. Zip_lzma)# Write a new file into the package, and data is the specific content of the file, either STR or byte. # here is a new BB folder, under which you create a new cc.txt, write Hello world to the text azip.writestr (' bb/cc.txt ', data=' Hello world ', Compress_type=zipfile. zip_deflated)# Close Resource azip.close ()            

There are two ways to compare similar, pay attention to distinguish.

    • writeRefers to copying an already existing file to a compressed package, including all files in the path Jia he the file under it.
    • writestris to create a new folder and file directly in the package, and the data parameter is the content to write to the file.

The final compressed package will be added to the BB folder, with aa.txtcc.txt

Add an entire folder to a compressed package

If we write like this, imagine being able to add all the contents of a BB folder to a compressed package, that's not right. This adds only the BB folder to the past, and only so, the files inside will not be added to the compressed package. The last to get is an empty folder.

azip.write(r‘D:/bb‘, compress_type=zipfile.ZIP_LZMA)

What about that? Had to recursive search added, os.walk just can help us.

for current_path, subfolders, filesname in os.walk(r‘D:\bb‘): print(current_path, subfolders, filesname) # filesname是一个列表,我们需要里面的每个文件名和当前路径组合 for file in filesname: # 将当前路径与当前路径下的文件名组合,就是当前文件的绝对路径 azip.write(os.path.join(current_path, file))# 关闭资源azip.close()

The correct selection of variables, the first in the tuple is the current path, and the third is the current path of the file, the combination of the two is exactly the absolute path of the file.

This enables you to add an entire folder to the compressed package. and all the folders under these paths and the files under them are all added. That is, the structure hierarchy of the original folder is preserved.

Shutil adding a compressed package and decompression

The SHUITL module has a function that allows you to easily add an entire entire folder to a compressed package.

# 第一个参数是归档文件名称,第二个参数是指定的格式,不仅是支持zip,第三个参数是要压缩文件/文件夹的路径shutil.make_archive(‘archive_name‘, ‘zip‘, r‘F:\IDE Setting‘)# shutil.get_archive_formats() 可以查看支持的格式

Of course, it can be decompressed, you can specify the decompression directory, or the default decompression to the current working directory .

shutil.unpack_archive(r‘D:\bb.zip‘)# shutil.get_unpack_formats() 可以查看支持的格式

Python Operation zip file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.