Dimitris Poulopoulos
Dimitris Poulopoulos

Reputation: 1159

Extract a file and rename it at the same time in python

I want to extract a file with a specific extension from my tarball file and at the same time give it a specific name. So far I can choose the file I want by extension and extract it. But how can I rename it the way I want?

tar = tarfile.open('files/compressed/compressed_file.tar.gz')
for member in tar.getmembers():
    if member.isfile() and member.name.endswith('.nii'):
        f = tar.extract(member, 'files/decompressed/')
    else:
        continue
tar.close()

Upvotes: 3

Views: 2788

Answers (1)

wnnmaw
wnnmaw

Reputation: 5514

Per the docs of the method you're using, the file object returned is read only. This means you will have to read in the data, then write it to another file just as you normally would. As you re-write the file you can name it how you want:

lines = f.readlines()

with open("your_filename_here.nii", 'w') as output:
    for line in lines:
        output.write(line)

Depending on how your file is formatted you may need to tweak the template above.

Upvotes: 1

Related Questions