HSHEKHAR
HSHEKHAR

Reputation: 43

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)

Upvotes: 0

Views: 416

Answers (1)

Şahin Murat Oğur
Şahin Murat Oğur

Reputation: 128

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}")

Upvotes: 0

Related Questions