使用Python编写一个简单的文件压缩器
发布时间:2023-12-04 16:01:31
下面是使用Python编写一个简单的文件压缩器的示例代码:
import zipfile
import os
def compress_folder(folder_path, output_path):
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.relpath(file_path, folder_path))
def compress_file(file_path, output_path):
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
zipf.write(file_path, os.path.basename(file_path))
# 使用示例:
if __name__ == '__main__':
folder_path = '/path/to/source/folder'
output_path = '/path/to/output/compressed.zip'
compress_folder(folder_path, output_path)
file_path = '/path/to/source/file.txt'
output_path = '/path/to/output/compressed.zip'
compress_file(file_path, output_path)
上述代码定义了两个函数 compress_folder 和 compress_file 来分别压缩目录和文件。compress_folder 函数将指定目录下的所有文件递归压缩到一个指定的压缩文件中,并保持文件的相对路径结构。compress_file 函数将指定的文件压缩到一个指定的压缩文件中。
在使用示例中,首先我们指定了要压缩的文件夹路径 folder_path 和输出的压缩文件路径 output_path,然后调用 compress_folder 函数来将文件夹压缩为 compressed.zip 文件。
接着,我们指定了要压缩的文件路径 file_path 和输出的压缩文件路径 output_path,然后调用 compress_file 函数将文件压缩为 compressed.zip 文件。
注意,示例中的路径需要根据实际情况进行修改。在实际使用时,你可以根据需要修改压缩算法和其他参数,并添加错误处理逻辑。
