gpt4 book ai didi

python - 如何在 python 中使用 shutil.make_archive 压缩文件?

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:03 25 4
gpt4 key购买 nike

我想使用 shutil.make_archive 命令压缩一个文本文件。我正在使用以下命令:

shutil.make_archive('gzipped'+fname, 'gztar', os.path.join(os.getcwd(), fname))

OSError: [Errno 20] Not a directory: '/home/user/file.txt'

我尝试了几种变体,但它一直试图压缩整个文件夹。如何正确地做到这一点?

最佳答案

实际上 shutil.make_archive可以制作单文件存档!只需将目标目录的路径作为 root_dir 并将目标文件名作为 base_dir 传递。

试试这个:

import shutil

file_to_zip = 'test.txt' # file to zip
target_path = 'C:\\test_yard\\' # dir, where file is

try:
shutil.make_archive(target_path + 'archive', 'zip', target_path, file_to_zip)
except OSError:
pass

关于python - 如何在 python 中使用 shutil.make_archive 压缩文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30049201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com