我需要一段压缩文件夹内所有文件的代码
以下是Python代码,可以压缩文件夹内的所有文件:
import zipfile
import os
def zipdir(path, ziph):
# Iterate through all the files in the directory
for root, dirs, files in os.walk(path):
for file in files:
# Create the full file path
file_path = os.path.join(root, file)
# Add the file to the ZIP archive
ziph.write(file_path, os.path.relpath(file_path, path))
if __name__ == '__main__':
# Set the directory path to be compressed
dir_path = "/path/to/folder"
# Set the name of the ZIP archive to be created
zip_file = "compressed.zip"
# Create a ZipFile object
zipf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
# Call the zipdir function to compress the directory
zipdir(dir_path, zipf)
# Close the ZipFile object
zipf.close()
将代码中的/path/to/folder替换为你要压缩的文件夹的路径,将compressed.zip替换为你想要创建的压缩文件的名称。运行代码后,程序将压缩文件夹中的所有文件,并将它们保存到指定的压缩文件中。
原文地址: https://www.cveoy.top/t/topic/bC1P 著作权归作者所有。请勿转载和采集!