pythonpython-3.xtar

Tar files convert in python


I have the following problem: i dont have Zipfiles. I have tar files. Can anyone help me please to change the code to tar files?

import glob
import os
from zipfile import ZipFile

zipfiles = [os.path.basename(x) for x in glob.glob(r'./*.zip')]

for zipfile in zipfiles:
    new_dirname = zipfile.replace('.bsw.', '_').replace('.zip', '')
    try:
        os.mkdir(f'output/{new_dirname}')
    except:
        print(f'output/{new_dirname} already exists')
    try:
        os.mkdir(f'output/{new_dirname}/subdir')
    except:
        print(f'output/{new_dirname}/subdir already exists')

    with ZipFile(f'./{zipfile}') as zipObject:
        zipObject.extractall(path=f'output/{new_dirname}/subdir')

Solution

  • zipfiles = [os.path.basename(x) for x in glob.glob('C:/Data/ODX/swfkbin/*')]
    
    for zipfile in zipfiles:
        new_dirname = zipfile.replace('.bin.', '_')
        #try:
        os.mkdir(f'output/{new_dirname}')
        #except:
        print(f'output/{new_dirname} already exists')
        #try:
        os.mkdir(f'output/{new_dirname}/full')
        #except:
        print(f'output/{new_dirname}/subdir already exists')
        #try:
        # your tar file
        tarfile = "your_tar_file_path"
        file = tarfile.open(tarfile)
        file.extractall('output/{new_dirname}/full')
        file.close()
        #except:
        print ("Not possible to extract")