将文件添加到现有zip文件

问题描述 投票:8回答:2

我正在使用python的zipfile模块。 将zip文件放在以下路径中: /home/user/a/b/c/test.zip/home/user/a/b/c/1.txt下创建另一个文件我想将此文件添加到现有zip文件中,我做了:

zip = zipfile.ZipFile('/home/user/a/b/c/test.zip','a')
zip.write('/home/user/a/b/c/1.txt')
zip.close()`

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

我也试过:zip.write(os.path.basename('/home/user/a/b/c/1.txt'))并且得到一个错误,该文件不存在,尽管它确实存在。

python zipfile
2个回答
13
投票

你非常接近:

zip.write(path_to_file, os.path.basename(path_to_file))

应该为你做的伎俩。

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

os.path.basename()为您删除路径中的目录,以便文件将以其名称存储在存档中。

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


0
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.