How To Loop Through Directories And Unzip Tar.gz Files?
I have a number of subdirectories that contain ...tar.gz files. I am trying to use os.walk() to go through the individual files and unzip them using the tarfile module. import os
Solution 1:
As explained in the os.walk
docs:
Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do
os.path.join(dirpath, name)
.
And of course you saw exactly that yourself, printing out alpha.tar.gz
, etc, which obviously aren't absolute pathnames or relative pathnames from the current working directory or anything else you could access, just bare filenames.
Also notice that every example given in the docs does exactly what's recommended. For example:
import osfor root, dirs, files inos.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
So, in your case:
for dirpath, dir, files inos.walk(top=current_wkd):
for file in files:
tar = tarfile.open(os.path.join(dirpath, file))
tar.extractall(path=output)
tar.close()
One more thing:
output_dir = '.../Tar_unzip/output'
This is almost certainly going to cause an error. For one thing, output
and output_dir
are not the same name. For another, ...
doesn't mean anything; you probably wanted ..
?
Post a Comment for "How To Loop Through Directories And Unzip Tar.gz Files?"