user2501825
user2501825

Reputation: 23

Extracting tar file with original time stamp

My objective is to extract archive file members to different location with original timestamps using python 2.6.

For example :

tar -tzvf nas_archive_11-15-12.tgz
-rw-r--r-- appins/app     2337 2012-11-15 10:25:09 nfs4exports/opt/prod/fmac/files/inbound/test_archive/a.txt.gpg

I want to restore above file to "/nfs4exports/opt/prod/fmac/files/inbound/test_archive/11-15-12/a.txt.gpg" since it was last modified on 15th November 2012.

I have created following script :

#!/usr/bin/python

import os, tarfile
from datetime import datetime, date, timedelta
import datetime

a_path = '/home/appins/.scripts/'

for root, subFolders, files in os.walk(a_path):
        for file in files:
           if file.startswith("nas_archive"):
                print file, " is getting extracted"
                mytar = tarfile.open(file)
                for member in mytar.getmembers():
                    if member.isreg():
                        myname = '/' + member.name
                        path_list = myname.rsplit('/')[1:]
                        print path_list
                        member.name = os.path.basename(member.name)
                        i_base = 'inbound'
                        i = -1
                        for index,value in enumerate(path_list):
                            if value == i_base:
                                i = index
                                break
                        if i == -1:
                            print i_base, " not found"
                        else:
                            path_list.insert(index + 2, '11-15-12')
                            path_list.remove(member.name)
                        print path_list
                        newpath = '/' +  os.path.join(*path_list)
                        print newpath
                        mytar.extract(member,newpath)

This script is working as expected but it extracting files with today's timestamps rather than original time stamp. Here I won't be able to use extractall method since i am calculating path separately for each file based on its original path. Is there a way for me to restore file to new location with original timestamps?

Upvotes: 0

Views: 3141

Answers (1)

Mattie B
Mattie B

Reputation: 21279

You need to look at the mtime attribute of TarInfo objects:

import tarfile
tar = tarfile.open('tarfile.tar')
for member in tar.getmembers():
    print member.name, member.mtime

Given the mtime value, you can use os.utime to set both the access and modification timestamps thus:

import os
os.utime('file', (mtime, mtime))

Upvotes: 2

Related Questions