【问题标题】:Adding file to existing zipfile将文件添加到现有 zipfile
【发布时间】:2016-03-20 03:26:16
【问题描述】:

我正在使用 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


    【解决方案1】:
    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)
    

    【讨论】:

    • 如果可以的话,我会给你更多的支持。此外,由于完整性,这需要成为公认的答案。
    【解决方案2】:

    你已经很接近了:

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

    应该为您解决问题。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多