如何在不添加目录层次结构的情况下使用 Python 将文件添加到 tarfile? [英] How can files be added to a tarfile with Python, without adding the directory hierarchy?

查看:28
本文介绍了如何在不添加目录层次结构的情况下使用 Python 将文件添加到 tarfile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我对具有文件路径的 tarfile 对象调用 add() 时,该文件将添加到具有关联目录层次结构的 tarball.换句话说,如果我解压 tarfile,原始目录层次结构中的目录将被复制.

When I invoke add() on a tarfile object with a file path, the file is added to the tarball with directory hierarchy associated. In other words, if I unzip the tarfile the directories in the original directories hierarchy are reproduced.

有没有办法简单地添加一个没有目录信息的纯文件,解压生成的 tarball 会生成一个平面文件列表?

Is there a way to simply adding a plain file without directory info that untarring the resulting tarball produce a flat list of files?

推荐答案

您可以使用 tarfile.addfile(),在 TarInfo 对象,它是第一个参数,您可以指定一个与您添加的文件不同的 name.

这段代码应该将 /path/to/filename 添加到 TAR 文件中,但会将其提取为 myfilename:

This piece of code should add /path/to/filename to the TAR file but will extract it as myfilename:

tar.addfile(tarfile.TarInfo("myfilename.txt"), open("/path/to/filename.txt"))

这篇关于如何在不添加目录层次结构的情况下使用 Python 将文件添加到 tarfile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆