Python:使用tarfile提取但忽略目录 [英] Python: Extract using tarfile but ignoring directories
本文介绍了Python:使用tarfile提取但忽略目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个带有文件 '/path/to/file.txt'
的 .tar 文件,有没有办法(在 Python 中)将文件解压缩到指定目录而无需重新创建目录 '/path/to'
?
If I have a .tar file with a file '/path/to/file.txt'
, is there a way (in Python) to extract the file to a specified directory without recreating the directory '/path/to'
?
推荐答案
我也遇到这个问题,根据ekhumoro的回答列出完整的例子
I meet this problem as well, and list the complete example based on ekhumoro's answer
import os, tarfile
output_dir = "."
tar = tarfile.open(tar_file)
for member in tar.getmembers():
if member.isreg(): # skip if the TarInfo is not files
member.name = os.path.basename(member.name) # remove the path by reset it
tar.extract(member,output_dir) # extract
这篇关于Python:使用tarfile提取但忽略目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文