I have some .tar.gz files and I can extract them with:
if (fname.endswith("tar.gz")):
tar = tarfile.open(fname, "r:gz")
tar.extractall()
tar.close()
But I want to add all the info of the extracted file in a .txt file, but I don't know the folders' name that .tar.gz files have inside to do it. Is it possible to know/rename the folders if you don't know the names and extract them? Thank you.
Each entry in the tarfile has a TarInfo
header. You can get that info several ways, the easiest is just by iteration. That includes the path name which you can manage with os.posixpath
functions. For example, given a tgz file I happen to have on hand:
>>> tf = tarfile.open("Downloads/dbutil-0.5.0.tar.gz", "r:gz")
>>> for info in tf:
... print(info.name, "DIR" if info.isdir() else "FILE")
...
dbutil-0.5.0 DIR
dbutil-0.5.0/setup.py FILE
dbutil-0.5.0/dbutil DIR
dbutil-0.5.0/dbutil/connection.py FILE
dbutil-0.5.0/dbutil/__init__.py FILE
dbutil-0.5.0/dbutil/row.py FILE
dbutil-0.5.0/PKG-INFO FILE
dbutil-0.5.0/dbutil.egg-info DIR
dbutil-0.5.0/dbutil.egg-info/dependency_links.txt FILE
dbutil-0.5.0/dbutil.egg-info/PKG-INFO FILE
dbutil-0.5.0/dbutil.egg-info/SOURCES.txt FILE
dbutil-0.5.0/dbutil.egg-info/top_level.txt FILE
dbutil-0.5.0/setup.cfg FILE