python - 在 Python 中将文件添加到 Tar 内的空目录

标签 python directory tar tarfile

在 Python 中,我尝试创建一个包含两个空目录的 tar,然后将文件列表添加到 tar 中的每个空目录。我在下面尝试过这样做,但它不起作用。

def ISIP_tar_files():
    with tarfile.open("eeg_files.tar", "w") as f:
        ep_dir = tarfile.TarInfo("Eplilepsy Reports")
    not_ep_dir = tarfile.TarInfo("Non Epilepsy Reports")
        ep_dir.type = not_ep_dir.type = tarfile.DIRTYPE
    f.addfile(ep_dir)
    f.addfile(not_ep_dir)
    with ep_dir.open():
            for name in ep_list:
        f.tarfile.add(name)

老实说,我不相信它会起作用,但值得一试,因为我在 Google 上找不到任何其他解决方案。这只是代码的一个模块,它不包括主程序或导入。 ep_list 是带有路径的文件列表,它看起来类似于:

ep_list = [/data/foo/bar/file.txt, /data/foo/bar2/file2.txt, ...]

有什么建议吗?

最佳答案

import tarfile
import os

ep_list = ['./foo/bar/file.txt', './foo/bar/file2.txt']

def ISIP_tar_files():
    with tarfile.open("eeg_files.tar", "w") as f:
        ep_dir = tarfile.TarInfo("Eplilepsy Reports")
        not_ep_dir = tarfile.TarInfo("Non Epilepsy Reports")
        ep_dir.type = not_ep_dir.type = tarfile.DIRTYPE
        ep_dir.mode = not_ep_dir.mode = 0o777
        f.addfile(ep_dir)
        f.addfile(not_ep_dir)
        for name in ep_list:
            f.add(name, arcname="Eplilepsy Reports/" + os.path.basename(name), recursive=False)

目录文件权限模式应该至少对于所有者来说是可执行的。否则无法提取。

  • arcname 是存档中文件的替代名称。
  • recursive表示是否保留递归添加的原始目录,默认值为True。

关于python - 在 Python 中将文件添加到 Tar 内的空目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953069/

相关文章:

python - TensorFlow:如何为 SavedModel 格式化 JSON,期望字符串格式的 3 个整数?

Java:JSON(Gson)从JSON字符串获取值

open-source - 开源主题/插件目录引擎

java - 使用 AWS Lambda 从 S3 上的目录创建 Tar 存档

python - 使用多列索引创建 Pandas Dataframe

python - 我如何确定 platform.release() 的可能返回值

c++ - 如何使用 C 或 C++ 获取目录中的文件列表?

python - QTreeWidget 中的目录树

python - 在 python 中解析 xml.gz 文件

linux - 仅 tar 目录中的文件