I am trying to make a script for unzipping all the .tar.gz files from folders in one directory. For example, I will have a file which it calls ( testing.tar.gz). Then if I do manually, I can press to "extract here" then the .tar.gz file will create a new file, and it calls testing.tar. Finally, if I repeat the process of pressing "extract here", the .tar file prodcudes me all the .pdf files.
I wonder that how can I do it, and I have my code here and it seems doesn't realty work tho.
import os import tarfile import zipfile def extract_file(path, to_directory='.'): if path.endswith('.zip'): opener, mode = zipfile.ZipFile, 'r' elif path.endswith('.tar.gz') or path.endswith('.tgz'): opener, mode = tarfile.open, 'r:gz' elif path.endswith('.tar.bz2') or path.endswith('.tbz'): opener, mode = tarfile.open, 'r:bz2' else: raise ValueError, "Could not extract `%s` as no appropriate extractor is found" % path cwd = os.getcwd() os.chdir(to_directory) try: file = opener(path, mode) try: file.extractall() finally: file.close() finally: os.chdir(cwd)
Import the zipfile module Create a zip file object using ZipFile class. Call the extract() method on the zip file object and pass the name of the file to be extracted and the path where the file needed to be extracted and Extracting the specific file present in the zip.
To open a compressed file in text mode, use open() (or wrap your GzipFile with an io. TextIOWrapper ).
You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.
Why do you want to "press" twice to extract a .tar.gz, when you can easily do it once? Here is a simple code to extract both .tar and .tar.gz in one go:
import tarfile if fname.endswith("tar.gz"): tar = tarfile.open(fname, "r:gz") tar.extractall() tar.close() elif fname.endswith("tar"): tar = tarfile.open(fname, "r:") tar.extractall() tar.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With