Python has the most abundant and powerful class libraries in the scripting language and is sufficient to support most daily applications. Python modules and C can work together and can be embedded into C or C ++ applications, therefore, the Python language can be used to provide script interfaces for applications.
Here we will record how to use zipfile. That is, it is convenient for you and others. Zipfile has two very important classes: ZipFile and ZipInfo. In most cases, we only need to use these two classes. The Python module ZipFile is the main class. It is used to create and read zip files, while ZipInfo stores the information of each file in the zip file.
For example, to read a zipfile, assume that filename is the path of a file:
- Import zipfile
-
- Z=Zipfile. ZipFile (filename, 'R') # Here, the second parameter is represented by r to read the zip file, and w is to create a zip file.
-
- For f in z. namelist ():
- Print f
- Import zipfile
-
- Z=Zipfile. ZipFile (filename, 'R ')
-
- For I in z. infolist ():
- Print I. file_size, I. header_offset
The Python module z. infolist () is used here. It returns the information of all the files in the compressed package, which is a ZipInfo list. A ZopInfo object contains information about a file in the compressed package. The commonly used file names are filename, file_size, and header_offset, respectively.
File size, which is the offset of file data in the compressed package. In fact, the previous z. namelist () is the filename in the read ZopInfo to form a list to return.
The ZipFile read method is used to extract a file from the compressed package:
The above is very simple. Think about another problem. What if I want to add a test/111.txt file to the package and put it in test22/111.txt?
- How to embed Python into C ++ applications?
- In-depth discussion of Ruby and Python syntax comparison
- Introduction to Python
- Python Learning Experience: version, IDE selection and coding Solutions
- Analysis of Python GIL and thread security