Anto
Anto

Reputation: 3896

tarfile extraction not working when a list of tar files are given in loop

I was trying to fetch list of tars and untar them one by one in a loop. Unfortunately getting below error.

#!/usr/bin/python3

import tarfile
import glob

name = "myself"
backup_path = "/tmp/test"

tar_location = backup_path+"/"+db+"/"
tar_list = glob.glob(tar_location + '/walfiles-*.tar.gz')

#Destination For Walfiles.
tar_destination = backup_path+"extracted"


# EXTRACT Tarfile


def extract_fn(tar,tar_destination):
  filename = str(tar)
  extract_destination = str(tar_destination)

  file_obj = tarfile.open(filename,"r")
  file = file_obj.extractall(extract_destination)
  file_obj.close()

for tarfile in tar_list:
  extract_fn(tarfile,tar_destination)

IMPORTANT: Confusing part is

  1. If I pass single set of values to extract_fn, it will work. Tar file will get extracted.
extract_fn("mytar.tar.gz",tar_destination)
  1. Then I thought, maybe for loop is not reading the LIST properly. So I tested it by removing tar commands and instead just print(tar) inside extract_fn. There was no issues.

  2. So I tried converting each list element to str then passed to funtion.

for tarfile in tar_list:
    filename = str(tarfile)
    extract_fn(filename,wal_destination)

STILL FAILING WITH same error.

ERROR:

>>> for tarfile in tar_list:
...     extract_fn(tarfile,tar_destination)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 5, in extract_fn
AttributeError: 'str' object has no attribute 'open'

I would like to have this extract function separately as I will need to somewhere else also. Still, what would be the reason for this kind of behavior?

Upvotes: 0

Views: 515

Answers (0)

Related Questions