将文件添加到现有的 zipfile [英] Adding file to existing zipfile
问题描述
我正在使用 python 的 zipfile
模块.
有一个位于以下路径的 zip 文件:/home/user/a/b/c/test.zip
并在 /home/user/a/b/c/1.txt
下创建另一个文件我想将此文件添加到现有的 zip,我做到了:
I'm using python's zipfile
module.
Having a zip file located in a path of:
/home/user/a/b/c/test.zip
And having another file created under /home/user/a/b/c/1.txt
I want to add this file to existing zip, I did:
zip = zipfile.ZipFile('/home/user/a/b/c/test.zip','a')
zip.write('/home/user/a/b/c/1.txt')
zip.close()`
解压文件时,所有子文件夹都出现在路径中,我如何只输入没有路径子文件夹的zip文件?
And got all the subfolders appears in path when unzipping the file, how do I just enter the zip file without path's subfolders?
我也试过:zip.write(os.path.basename('/home/user/a/b/c/1.txt'))
并得到文件不存在的错误,尽管它确实存在.
I tried also :
zip.write(os.path.basename('/home/user/a/b/c/1.txt'))
And got an error that file doesn't exist, although it does.
推荐答案
你已经很接近了:
zip.write(path_to_file, os.path.basename(path_to_file))
应该为您解决问题.
说明:zip.write
函数接受第二个参数(弧名),它是要存储在 zip 存档中的文件名,请参阅 zipfile 更多详情.
Explanation: The zip.write
function accepts a second argument (the arcname) which is the filename to be stored in the zip archive, see the documentation for zipfile more details.
os.path.basename()
为您删除路径中的目录,以便文件将仅以其名称存储在存档中.
os.path.basename()
strips off the directories in the path for you, so that the file will be stored in the archive under just it's name.
请注意,如果您仅 zip.write(os.path.basename(path_to_file))
它将在当前目录中查找该文件(如错误所述)不存在的文件.
Note that if you only zip.write(os.path.basename(path_to_file))
it will look for the file in the current directory where it (as the error says) does not exist.
这篇关于将文件添加到现有的 zipfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!