我正在尝试在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
压缩文件的正确方法是:
zipfile.ZipFile('hello.zip', mode='w').write("hello.csv")
# assume your xxx.py under the same dir with hello.csv
python官方文档说:
ZipFile.write(filename, arcname=None, compress_type=None)
将名为filename的文件写入存档,为其指定存档名称arcname
您open(filename).read()
进入write()
。open(filename).read()
是包含文件全部内容的单个字符串,由于它试图查找以字符串内容命名的文件filename
而将抛出FileNotFoundError
该字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句