我想使用 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
我是一名优秀的程序员,十分优秀!