【问题标题】:How to change the output folder using ZipFile?如何使用 ZipFile 更改输出文件夹?
【发布时间】:2022-01-01 15:04:59
【问题描述】:

我需要根据 excel 中的列表将每个单独的文件从一个文件夹 (Location1) 压缩到另一个文件夹 (Location2),但目前我遇到了一个问题,即我的 zip 文件的输出被放置在根文件夹.

这是我的代码。

DirectorySource = 'D:\Location1'

DirectoryDestination = 'D:\Location2'

data = openpyxl.load_workbook(r'D:\File_List.xlsx')
df = data['Sheet1']
        
for i in range(2, df.max_row + 1):
           cell_obj = df.cell(row=i, column = 1)
           ZipFile(cell_obj.value+'.zip',mode='w').write(DirectorySource+'/'+cell_obj.value+'.txt',
           basename(DirectorySource+'/'+cell_obj.value+'.txt'),compress_type=ZIP_DEFLATED)

我该如何解决这个问题?

【问题讨论】:

  • 如果你想在不同的文件夹中使用/path/file.zip in ZipFile(...) - write() 不会更改磁盘上的文件夹,但会更改 zip 文件中的文件夹。
  • 我不知道你为什么使用basename - 它应该给你cell_obj.value+'.txt' 没有DirectorySource - 所以你可以直接使用cell_obj.value+'.txt'

标签: python zip python-zipfile


【解决方案1】:

要将.zip 文件放在不同的文件夹中,您必须使用ZipFile 中的路径,而不是write 中的路径

destination  = os.path.join(DirectoryDestination, cell_obj.value+'.zip')

ZipFile(destination, ...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2017-03-23
    • 2012-02-16
    • 2018-04-09
    • 2020-05-03
    相关资源
    最近更新 更多