python,压缩指定目录
时间: 2023-08-04 10:33:44 浏览: 39
你可以使用 Python 内置的 zipfile 模块来压缩指定目录。以下是一个示例代码:
```python
import zipfile
import os
def zipdir(path, ziph):
# Iterate over all the files in directory
for root, dirs, files in os.walk(path):
for file in files:
# Create absolute path for the file
abs_path = os.path.join(root, file)
# Add the file to the zip
ziph.write(abs_path, arcname=os.path.relpath(abs_path, path))
# Define the directory to be zipped
dir_path = '/path/to/directory'
# Define the name of the zip file
zip_file_name = 'archive.zip'
# Create a zipfile object
zipf = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
# Zip the directory
zipdir(dir_path, zipf)
# Close the zipfile object
zipf.close()
```
在上面的代码中,zipdir() 函数递归遍历指定目录中的文件,并将每个文件添加到 zip 文件中。在添加文件到 zip 文件时,我们使用了 `os.path.relpath()` 函数,以使文件在 zip 文件中的路径与其在原始目录中的路径一致。最后,我们使用 zipfile.ZipFile() 函数创建一个 zip 文件对象,将指定的目录压缩成一个 zip 文件,然后关闭 zip 文件对象。