Skip to content

Instantly share code, notes, and snippets.

@vsoch vsoch/editTarfile.py
Last active Nov 14, 2018

Embed
What would you like to do?
example of opening and editing a .tar.gz (change permissions in this case)
import tarfile
import tempfile
import stat
import os
tar_file = "input.tar.gz"
tar = tarfile.open(tar_file, "r:gz")
members = tar.getmembers()
file_permission = stat.S_IRUSR | stat.S_IWUSR
folder_permission = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
# Let's pretend we want to edit, and write to new tar
if len(members) > 0:
fd, tmp_tar = tempfile.mkstemp(prefix=("%s.fixed." % tar_file))
os.close(fd)
fixed_tar = tarfile.open(tmp_tar, "w:gz")
# Then process members
for member in members:
# add o+rwx for directories
if member.isdir() and not member.issym():
member.mode = folder_permission | member.mode
extracted = tar.extractfile(member)
fixed_tar.addfile(member, extracted)
# add o+rw for plain files
elif member.isfile() and not member.issym():
member.mode = file_permission | member.mode
extracted = tar.extractfile(member)
fixed_tar.addfile(member, extracted)
else:
fixed_tar.addfile(member)
fixed_tar.close()
tar.close()
# Rename the fixed tar to be the old name
os.rename(tmp_tar, tar_file)
else:
tar.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.