我试图用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
由于还想指定目录,请尝试使用
os.chdir
:压缩文件的正确方法是:
python官方文档says:
您将
open(filename).read()
传递到write()
。open(filename).read()
是一个包含文件filename
的全部内容的字符串,它将抛出FileNotFoundError
,因为它试图找到一个用字符串内容命名的文件。如果要压缩的文件(
filename
)位于名为pathname
的不同目录中,则应使用arcname
参数。否则,它将重新创建文件文件夹的完整文件夹层次结构。相关问题 更多 >
编程相关推荐