python - 创建 zip 文件时出现嵌套目录

标签 python zip

我对 python 很陌生。这里我尝试创建“diveintomark-diveintopython3-793871b”目录的 zip 文件。我使用 os.chdir() 函数更改了当前工作目录。zip 文件已创建,但出现问题当我解压 zip 文件时,我得到以下目录

Users/laiba/Desktop/diveintomark-diveintopython3-793871b 

但我只想要 zip 文件夹中的 diveintomark-diveintopython3-793871b 文件夹,而不是创建的整个嵌套目录。为什么会发生这种情况以及如何解决这个问题?

import zipfile, os

os.chdir('c:\\Users\\laiba\\Desktop')
myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
    myzip.write(folder)
    for each in subfolder:
        myzip.write(os.path.abspath(os.path.join(folder,each)))
    for each in file:
        myzip.write(os.path.abspath(os.path.join(folder,each)))

最佳答案

您可以使用参数arcname:存档中项目的名称,而不是完整路径名。但在这里您不需要它,因为您已经位于正确的目录中。只需删除 abspath 即可完成(以及重复的文件夹条目)

import zipfile, os

os.chdir('c:\\Users\\laiba\\Desktop')

myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
    for each in subfolder+file:
        myzip.write(os.path.join(folder,each))
myzip.close()

这可以在不更改目录的情况下完成,但更复杂,也更优雅,因为您不必 chdir

import zipfile, os

root_dir = r"c:\Users\laiba\Desktop"
myzip=zipfile.ZipFile(os.path.join(root_dir,'diveZip.zip'),'w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk(os.path.join(root_dir,'diveintomark-diveintopython3-793871b')):
    for each in subfolder+file:
        source = os.path.join(folder,each)
        # remove the absolute path to compose arcname
        # also handles the remaining leading path separator with lstrip
        arcname = source[len(root_dir):].lstrip(os.sep)
        # write the file under a different name in the archive
        myzip.write(source,arcname=arcname)

myzip.close()

关于python - 创建 zip 文件时出现嵌套目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39424402/

相关文章:

python - 用中位数对缺失值进行插补

python - 在 Django 单元测试中查询数据库

c - 用 C 直接读写压缩文件

c# - 在 ZipFile 中添加大量文件时出现 OutOfMemoryException

python如何附加到zip存档中的文件

python - WrapSize 和滚动条 : widgets not drawn at startup won't draw later

python - 单向链表的反向链接方向

python - 通过日志记录更新 QTextEdit 时 PyQt5 程序崩溃

python - python 中的压缩列表

r - 在 R 中 gunzip 文件流?