我正在使用以下代码来提取一个tar文件:
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
然而,我希望以目前正在提取哪些文件的形式掌握进展情况。我该如何做到这一点?
额外奖励分数:能否创建提取过程的百分比?我想将其用于tkinter更新进度条。谢谢!
文件进度和全局进度:
import io
import os
import tarfile
def get_file_progress_file_object_class(on_progress):
class FileProgressFileObject(tarfile.ExFileObject):
def read(self, size, *args):
on_progress(self.name, self.position, self.size)
return tarfile.ExFileObject.read(self, size, *args)
return FileProgressFileObject
class TestFileProgressFileObject(tarfile.ExFileObject):
def read(self, size, *args):
on_progress(self.name, self.position, self.size)
return tarfile.ExFileObject.read(self, size, *args)
class ProgressFileObject(io.FileIO):
def __init__(self, path, *args, **kwargs):
self._total_size = os.path.getsize(path)
io.FileIO.__init__(self, path, *args, **kwargs)
def read(self, size):
print("Overall process: %d of %d" %(self.tell(), self._total_size))
return io.FileIO.read(self, size)
def on_progress(filename, position, total_size):
print("%s: %d of %s" %(filename, position, total_size))
tarfile.TarFile.fileobject = get_file_progress_file_object_class(on_progress)
tar = tarfile.open(fileobj=ProgressFileObject("a.tgz"))
tar.extractall()
tar.close()
tqdm()
函数并打印提取的文件数量的进度:import tarfile
from tqdm import tqdm
# open your tar.gz file
with tarfile.open(name=path) as tar:
# Go over each member
for member in tqdm(iterable=tar.getmembers(), total=len(tar.getmembers())):
# Extract member
tar.extract(member=member)
extractall()
中指定members
参数。with tarfile.open(<path>, 'r') as tarball:
tarball.extractall(path=<some path>, members = track_progress(tarball))
def track_progress(members):
for member in members:
# this will be the current file being extracted
yield member
member
是 TarInfo
对象,查看所有可用的函数和属性请点击此处
yield member
后面,你可以打印出名称或更新进度条。 - Xiong Chiamiovextract
替代 extractall
- 这样您就能够在文件被提取时打印成员名称。要获取成员列表,您可以使用 getmembers。要查看当前正在提取的文件,以下方法适用:
import tarfile
print "Extracting the contents of sample.tar.gz:"
tar = tarfile.open("sample.tar.gz")
for member_info in tar.getmembers():
print "- extracting: " + member_info.name
tar.extract(member_info)
tar.close()
这是我使用的方法,无需猴子补丁或需要条目数量。
def iter_tar_files(f):
total_bytes = os.stat(f).st_size
with open(f, "rb") as file_obj,\
tarfile.open(fileobj=file_obj, mode="r:gz") as tar:
for member in tar.getmembers():
f = tar.extractfile(member)
if f is not None:
content = f.read()
yield member.path, content
# This prints something like: 512/1024 = 50.00%
print(f"{file_obj.tell()} / {total_bytes} = {file_obj.tell()/total_bytes*100:.2f}%")