Extracting file from tarfile with only basename using Python

这一生的挚爱 提交于 2019-12-11 08:10:34

问题


I have a 'tafile' which contains files with complete path '/home/usr/path/to/file'. When I extract the file to the curent folder it creates the complete path recursively. Is there a way that I can extract the file with only the base name.


回答1:


Use TarFile.extractfile() and write it into a file of your choice.




回答2:


You can change the arcnames by hacking the TarInfo objects you get from Tarfile.getmembers(). Then you can use Tarfile.extractall to write the members to your chosen destination under their new names.

E.g., the following function will select members from an arbitrary subtree of the archive and extract them to a destination under their base names:

def extractTo(tar, dest, selector):
    if type(selector) is str:
        prefix = selector
        selector = lambda m: m.name.startswith(prefix)
    members = [m for m in tar.getmembers() if selector(m)]
    for m in members:
        m.name = os.path.basename(m.name)
    tar.extractall(path = dest, members = members)

Suppose tar is a TarFile instance representing an archive with some members in a utilities/misc directory, and you would like to fold those members into the local/bin directory. You could do:

extractTo(tar, 'local/bin', 'utilities/misc/')

Note the trailing / on the directory prefix. We don't want to add the misc directory to `local/bin', rather, just its members.




回答3:


You can use the functionextractall to fit your needs. According to the documentation : Extract all members from the archive to the current working directory or directory path.

TarFile.extractall(path="my/path")


来源:https://stackoverflow.com/questions/6149457/extracting-file-from-tarfile-with-only-basename-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!