[英]Append a file to a ZipFile in python
First I created a new zipfile: 首先,我创建了一个新的zipfile:
import zipfile
zf = zipfile.ZipFile('/data2/new.zip', mode='w')
then I wanted to append a file into the newly created zipfile, say download.py
in another folder: 然后我想将文件附加到新创建的zip文件中,例如在另一个文件夹中说download.py
:
zf.write('/data2/another_folder/download.py')
All seemed fine until I unzip it locally and I found that it did not just append the file, but also append all the folders, data2
and another_folder
. 在我将其解压缩到本地之前,一切似乎都还不错,我发现它不仅附加了文件,还附加了所有文件夹, data2
和another_folder
。 I have to open /data2/new/data2/another_folder/
to find download.py
. 我必须打开/data2/new/data2/another_folder/
来找到download.py
。
I want to append and only append the file to zipfile. 我要附加文件,并且仅将文件附加到zipfile。 How can I avoid the aforementioned situation? 如何避免上述情况?
Thanks in advance. 提前致谢。
The zipfile.write()
method takes an optional arcname
argument that specifies what the name of the file should be inside the zipfile. zipfile.write()
方法采用可选的arcname
参数,该参数指定zipfile中文件的名称。
import os
import zipfile
zf.write('/data2/another_folder/download.py', 'download.py')
zf.close()
Here's a function to zip multiple files together: 这是将多个文件压缩在一起的功能:
def zip(list_of_file_paths):
zf = zipfile.ZipFile("Zipfile.zip", "w", zipfile.ZIP_DEFLATED)
for path in list_of_file_paths:
filename = os.path.basename(os.path.normpath(path))
zf.write(path, filename)
zf.close()
zip(['path/to/file1', 'path/to/file2', ...]
zf.write('path/to/file.txt', arcname='name_without_path.txt')
should solve that for you, if you want to keep the same name without the path you can also do this: 应该为您解决此问题,如果您要保留相同的名称而没有路径,也可以这样做:
filepath = 'path/to/file.txt'
zf.write(filepath, arcname=os.path.basename(filepath))
that assumes you did import os
of course 假设您确实import os
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.