min*_*als 6 python compression
我想使用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'
Run Code Online (Sandbox Code Playgroud)
我尝试了几种变体,但它一直试图压缩整个文件夹。如何正确地做到这一点?
Com*_*nse 14
居然shutil.make_archive可以做成一档存档!只需将路径传递到目标目录 asroot_dir和目标文件名 as 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
Run Code Online (Sandbox Code Playgroud)
小智 5
shutil无法从一个文件创建存档。您可以使用tarfile, 代替:
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
os.chdir('/home/user')
tar.add("file.txt")
tar.close()
Run Code Online (Sandbox Code Playgroud)
或者
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
tar.addfile(tarfile.TarInfo("/home/user/file.txt"), "/home/user/file.txt")
tar.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13629 次 |
| 最近记录: |