【问题标题】:zip a folder with all its content without preserving directory structure in Python压缩包含所有内容的文件夹,而不保留 Python 中的目录结构
【发布时间】:2020-12-01 12:51:13
【问题描述】:

我有目录,里面有很多 csv 文件。当我尝试使用 zipfile 或 shutil 包压缩文件夹时,会创建一个完整的目录结构。我只需要获取压缩了很多 csv 文件的文件夹。

【问题讨论】:

  • 也许你想发布一个minimal reproducible example 来展示你目前在做什么。
  • 如果我理解正确,您想要一个仅包含 csv 文件但不包含目录的 zip,对吗?
  • 我有像数据/最终数据/csv文件这样的项目结构。执行 zip 时我需要的解决方案是 data.zip,解压缩后应该给我们最终数据/csv 文件

标签: python zipfile shutil


【解决方案1】:
import shutil
import os


def make_archive(source, destination):
    base = os.path.basename(destination)
    name = base.split(".")[0]
    format = base.split(".")[1]
    archive_from = os.path.dirname(source)
    archive_to = os.path.basename(source.strip(os.sep))
    shutil.make_archive(name, format, archive_from, archive_to)
    shutil.move("%s.%s" % (name, format), destination)


make_archive("/Users/myusername/Documents/my_folder", "/Users/myusername/Desktop/data.zip")

在我的 Documents 文件夹中,我有 my_folder,其中包含所有 csv 文件。我将其压缩并放到名为data.zip 的桌面上。解压后是my_folder/all your csv files

【讨论】:

  • 嗨,上面创建了一个包含所有 csv 的 zip 文件。但是如果我解压缩,我需要 my_folder/all csv 文件吗
  • 如果您使用上面的代码,您会在解压缩时注意到它会解压缩一个名为myfile/all csv files 的文件夹,这正是您想要的对吗?
  • 嗨,我仍然看到相同的输出,当解压缩时会显示没有文件夹的 csv 文件
  • @viswanaththatha 试试上面的,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
  • 2020-12-18
相关资源
最近更新 更多