【发布时间】:2018-11-13 02:13:21
【问题描述】:
所以基本上我有一个这样的文件系统:
main_archive.tar.gz
main_archive.tar
sub_archive.xml.gz
actual_file.xml
这个存档中有数百个文件...所以基本上,gzip 包可以与 Python 3 中的多个文件一起使用吗?我只将它与一个压缩文件一起使用,所以我不知道如何遍历多个文件或多个级别的“压缩”。
我常用的解压方法是:
with gzip.open(file_path, "rb") as f:
for ln in f.readlines():
*decode encoding here*
当然,这有很多问题,因为通常“f”只是一个文件……但现在我不确定它代表什么?
任何帮助/建议将不胜感激!
编辑 1:
我已经接受了下面的答案,但是如果您正在寻找类似的代码,我的主干基本上是:
tar = tarfile.open(file_path, mode="r")
for member in tar.getmembers():
f = tar.extractfile(member)
if verbose:
print("Decoding", member.name, "...")
with gzip.open(f, "rb") as temp:
decoded = temp.read().decode("UTF-8")
e = xml.etree.ElementTree.parse(decoded).getroot()
for child in e:
print(child.tag)
print(child.attrib)
print("\n\n")
tar.close()
使用的主要包是gzip、tarfile和xml.etree.ElementTree。
【问题讨论】:
标签: python python-3.x character-encoding gzip compression