压缩单fi

2024-09-27 09:36:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python压缩一个文件。不管是什么原因,我都很难理解语法。我要做的是保留原始文件并创建原始文件的新压缩文件(就像Mac或Windows在存档文件时所做的那样)。

以下是我目前掌握的情况:

import zipfile

myfilepath = '/tmp/%s' % self.file_name
myzippath = myfilepath.replace('.xml', '.zip')

zipfile.ZipFile(myzippath, 'w').write(open(myfilepath).read()) # does not zip the file properly

Tags: 文件importwindowsmac语法情况原因zip
3条回答

由于还想指定目录,请尝试使用os.chdir

#!/usr/bin/python

from zipfile import ZipFile
import os

os.chdir('/path/of/target/and/destination')
ZipFile('archive.zip', 'w').write('original_file.txt')

压缩文件的正确方法是:

zipfile.ZipFile('hello.zip', mode='w').write("hello.csv")
# assume your xxx.py under the same dir with hello.csv

python官方文档says

ZipFile.write(filename, arcname=None, compress_type=None)

Write the file named filename to the archive, giving it the archive name arcname

您将open(filename).read()传递到write()open(filename).read()是一个包含文件filename的全部内容的字符串,它将抛出FileNotFoundError,因为它试图找到一个用字符串内容命名的文件。

如果要压缩的文件(filename)位于名为pathname的不同目录中,则应使用arcname参数。否则,它将重新创建文件文件夹的完整文件夹层次结构。

from zipfile import ZipFile
import os

with ZipFile(zip_file, 'w') as zipf:
    zipf.write(os.path.join(pathname,filename), arcname=filename)

相关问题 更多 >

    热门问题