将文件添加到现有zipfile

Jav*_*aSa 11 python zipfile

我正在使用python的zipfile模块.
将zip文件放在以下路径中:
/home/user/a/b/c/test.zip
/home/user/a/b/c/1.txt 我想要将此文件添加到现有zip的情况下创建另一个文件时,我做了:
zip.write(os.path.basename('/home/user/a/b/c/1.txt'))

在解压缩文件时,所有子文件夹都出现在路径中,如何在没有路径的子文件夹的情况下输入zip文件?

我也尝试过: zipfile 并且得到了一个错误,该文件不存在,尽管它确实存在.

注意:我没有在路径中使用硬编码值,在本例中只是为了简化它.

Mar*_*oma 16

import zipfile

# Open a zip file at the given filepath. If it doesn't exist, create one.
# If the directory does not exist, it fails with FileNotFoundError
filepath = '/home/user/a/b/c/test.zip'
with zipfile.ZipFile(filepath, 'a') as zipf:
    # Add a file located at the source_path to the destination within the zip
    # file. It will overwrite existing files if the names collide, but it
    # will give a warning
    source_path = '/home/user/a/b/c/1.txt'
    destination = 'foobar.txt'
    zipf.write(source_path, destination)
Run Code Online (Sandbox Code Playgroud)

  • 如果可以的话,我会给你更多的支持。此外,由于完整性,这需要成为公认的答案。 (3认同)

lab*_*lab 14

你非常接近:

zip.write(path_to_file, os.path.basename(path_to_file))
Run Code Online (Sandbox Code Playgroud)

应该为你做的伎俩.

说明:该zip.write函数接受第二个参数(arcname),该参数是要存储在zip存档中的文件名,请参阅zipfile文档更多详细信息.

os.path.basename() 剥离路径中的目录,以便将文件以其名称存储在存档中.

请注意,如果您只是zip.write(os.path.basename(path_to_file))它将查找当前目录中的文件(如错误所示)不存在.