Extract Tar File with Txz Format in Python

Is there any way to extract file(filename.log.txz) with extension txz and list folder/filename after extraction in python. I tried with module tarfile which throwing error "AttributeError: module 'tarfile' has no attribute 'open'".

Note: My expectation is to extract txz file list all files/folder inside extracted file and look for required filename.

Python version: 3.6.8`

code****

import os
import tarfile

filename = sys.argv[1]
print(filename)

file1 = tarfile.open('{}'.format(filename), 'r')
file1.extract('path where to extract')
file1.close()

Error:

Traceback (most recent call last): File "tarfile.py", line 3, in import tarfile File "/path/tarfile.py", line 8, in file1 = tarfile.open('{}'.format(filename), 'r') AttributeError: module 'tarfile' has no attribute 'open'

Solution:

import os
import subprocess

filename = sys.argv[1]
print(filename)

subprocess.check_output("tar -xvf {filename}", shell=True)

d = os.listdir()

print(d)
3

1 Answer

Maybe you can try something like that

import os

for  file_name in os.listdir():
    if file_name.endswith(".txz"):
        os.system(f"tar -zxvf {file_name}")
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest