zipfile.ZipFile
时间: 2023-09-04 22:16:21 浏览: 99
Python 实现的解压缩工具-zipfile.exe
The `zipfile.ZipFile` class in Python is used to create, read, write and extract files from zip archives.
To create a `ZipFile` object, you can pass the path of the zip archive as a string to the constructor. For example:
```python
import zipfile
with zipfile.ZipFile('example.zip', 'w') as myzip:
myzip.write('file1.txt')
myzip.write('file2.txt')
```
In this example, we create a new zip archive named `example.zip` and add two files `file1.txt` and `file2.txt` to it.
To read or extract files from a zip archive, you can use the `ZipFile` object's `read()` or `extract()` method, respectively. For example:
```python
import zipfile
with zipfile.ZipFile('example.zip', 'r') as myzip:
myzip.extract('file1.txt', path='extracted_files')
```
In this example, we extract the file `file1.txt` from the `example.zip` archive to a directory named `extracted_files`.
The `ZipFile` class also provides methods to add, delete and modify files in the archive, as well as to access information about the archive and its contents.
阅读全文