Re: extract from zip files.. | Newbie | | Join Date: Feb 2007
Posts: 8
| |
hello, i am quite new to python and i have been experimenting with the zipfile module since i deal with a lot of zip files everyday and i want to automate my work..my question is: how do i retain the date and time stamp of the files that i have 'unzipped' from the zip file..i already know how to unzip but a new timestamp is written (time and day unzipped)..it is important that i retain the original from the zipfile..can someone help me out?thanks in advance.. :) been trying to solve this myself but the solution keeps on evading me.. -
def unzip(zip,dst,name):
-
zip = zipfile.ZipFile(zip, 'r')
-
os.makedirs(dst+name)
-
dst = dst+name
-
for filename in zip.namelist():
-
bytes = zip.read(filename)
-
print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
-
file((join(dst,filename)), 'wb').write(zip.read(filename))
-
zip.close
-
btw,am using windows xp with py2.4.4..
| | Expert | | Join Date: Apr 2006
Posts: 512
| | | re: Re: extract from zip files.. Quote:
Originally Posted by crashonyou hello, i am quite new to python and i have been experimenting with the zipfile module since i deal with a lot of zip files everyday and i want to automate my work..my question is: how do i retain the date and time stamp of the files that i have 'unzipped' from the zip file..i already know how to unzip but a new timestamp is written (time and day unzipped)..it is important that i retain the original from the zipfile..can someone help me out?thanks in advance.. :) been trying to solve this myself but the solution keeps on evading me.. -
def unzip(zip,dst,name):
-
zip = zipfile.ZipFile(zip, 'r')
-
os.makedirs(dst+name)
-
dst = dst+name
-
for filename in zip.namelist():
-
bytes = zip.read(filename)
-
print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
-
file((join(dst,filename)), 'wb').write(zip.read(filename))
-
zip.close
-
btw,am using windows xp with py2.4.4..
how about giving the tar module a try here
tarring before zipping can keep time stamps..
|  | Moderator | | Join Date: Jan 2007 Location: Maine, USA
Posts: 2,904
| | | re: Re: extract from zip files..
Welcome to theScripts.
I believe you can set these timestamps using the utime() function.
| | Newbie | | Join Date: Feb 2007
Posts: 8
| | | re: Re: extract from zip files..
thanks guys..ill try tar as suggested..right now im using the zipfile module when i write the zip file and the time stamp is well preserved..am confused about the extract part though cos i want to retain the time stamp.. i have tried utime but im having a hard time binding the values to mtime which i got from getinfo..i guess ill do this a bit more till i get it but if i don't,ill be back..thanks a bunch again.. :)
correct me if im wrong, i can use any time value for atime when i use utime, right?
EDIT: by the way,its my 1st time in this forum and i am impressed..i hope to find
a home here..thanks Motoma :)
|  | Moderator | | Join Date: Sep 2006 Location: Minden, Nevada, USA
Posts: 6,400
| | | re: Re: extract from zip files.. Quote:
Originally Posted by crashonyou thanks guys.. by the way,its my 1st time in this forum and i am impressed..i hope to find
a home here.. :) Definitely! Keep posting,
Barton
| | Newbie | | Join Date: Feb 2007
Posts: 8
| | | re: Re: extract from zip files..
woaah!!i finally got it..hehehe..thanks for the tips guys..i just used zipfile module without tarring..and i can unzip files with ([folders within folders]raised to the power of n)..hehehe..python is so amazing!!im shy about posting my code here just yet since im a newbie but if anyone wants it,id be happy to..thanks again.. :)
|  | Moderator | | Join Date: Sep 2006 Location: Minden, Nevada, USA
Posts: 6,400
| | | re: Re: extract from zip files.. Quote:
Originally Posted by crashonyou woaah!!i finally got it..hehehe..thanks for the tips guys..i just used zipfile module without tarring..and i can unzip files with ([folders within folders]raised to the power of n)..hehehe..python is so amazing!!im shy about posting my code here just yet since im a newbie but if anyone wants it,id be happy to..thanks again.. :) The whole community benefits from your posts. (just imagine the next person in the position that you were in before you posted) So, yes, definitly post for everybody's sake. Thanks.
| | Newbie | | Join Date: Feb 2007
Posts: 8
| | | re: Re: extract from zip files..
here is my script..any comment is appreciated..i personally think its too long but it does what i need it to do..i can't retain folder time stamps though and i think its not possible since windows and winzip(the ones ive tried)also writes new timestamps to folders when unzipping from the zipfile..if u guys know how to do it, please let me know.. :) any 'constructive' comments and suggestions for this script will be appreciated..it will add to my programming skills..hehehe..thanks in advance guys.. ps..im trying something new right now..how do i zip all files and folders(recursive) inside a folder to a zip file..ill search around the forums
more but if anyone can help me out,you are heaven-sent..thanks!! -
import zipfile, os, time, datetime, os.path
-
from zipfile import *
-
from os import *
-
from os.path import *
-
from time import mktime
-
-
## Zipfile to be unzipped
-
zips = 'test.zip'
-
## Destination directory
-
dst = ''
-
## Specific folder in destination
-
name = 'test'
-
-
zip = zipfile.ZipFile(zips, 'r')
-
if os.path.exists(dst+name):
-
pass
-
else:
-
os.makedirs(dst+name)
-
dst = dst+name+'/'
-
for filename in zip.namelist():
-
if filename.endswith('/'):
-
if os.path.exists(join(abspath(dst),filename)):
-
pass
-
else:
-
os.makedirs(join(abspath(dst),filename))
-
else:
-
try:
-
os.makedirs(normpath((abspath(dst)+'/'+dirname(filename))))
-
try:
-
bytes = zip.read(filename)
-
print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
-
file((join(dst,filename)), 'wb').write(zip.read(filename))
-
accesstime = time.time()
-
timeTuple=(int(zip.getinfo(filename).date_time[0]),\
-
int(zip.getinfo(filename).date_time[1]),\
-
int(zip.getinfo(filename).date_time[2]),\
-
int(zip.getinfo(filename).date_time[3]) ,\
-
int(zip.getinfo(filename).date_time[4]),\
-
int(zip.getinfo(filename).date_time[5]),\
-
int(0),int(0),int(0))
-
modifiedtime = mktime(timeTuple)
-
utime((join(dst,filename)), (accesstime,modifiedtime))
-
except IOError:
-
pass
-
except:
-
if os.path.exists(normpath((abspath(dst)+'/'+dirname(filename)))):
-
try:
-
bytes = zip.read(filename)
-
print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
-
file((join(dst,filename)), 'wb').write(zip.read(filename))
-
accesstime = time.time()
-
timeTuple=(int(zip.getinfo(filename).date_time[0]),\
-
int(zip.getinfo(filename).date_time[1]),\
-
int(zip.getinfo(filename).date_time[2]),\
-
int(zip.getinfo(filename).date_time[3]) ,\
-
int(zip.getinfo(filename).date_time[4]),\
-
int(zip.getinfo(filename).date_time[5]),\
-
int(0),int(0),int(0))
-
modifiedtime = mktime(timeTuple)
-
utime((join(dst,filename)), (accesstime,modifiedtime))
-
except IOError:
-
pass
-
else:
-
os.makedirs(normpath((abspath(dst)+'/'+dirname(filename))))
-
zip.close
-
|  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,560
| | | re: Re: extract from zip files.. Quote:
Originally Posted by crashonyou here is my script..any comment is appreciated..i personally think its too long but it does what i need it to do..i can't retain folder time stamps though and i think its not possible since windows and winzip(the ones ive tried)also writes new timestamps to folders when unzipping from the zipfile..if u guys know how to do it, please let me know.. :) any 'constructive' comments and suggestions for this script will be appreciated..it will add to my programming skills..hehehe..thanks in advance guys.. ps..im trying something new right now..how do i zip all files and folders(recursive) inside a folder to a zip file..ill search around the forums
more but if anyone can help me out,you are heaven-sent..thanks!!
This function will return a joined list as a string of all the files found under a given directory. In this case it passes files that do not have a 'py' extension: - import os
-
-
# Joined string method
-
-
def dir_list2(dir_name, *args):
-
fileList = []
-
for file in os.listdir(dir_name):
-
dirfile = os.path.join(dir_name, file)
-
if os.path.isfile(dirfile):
-
if len(args) == 0:
-
fileList.append('%s\n' %(dirfile))
-
else:
-
if os.path.splitext(dirfile)[1][1:] in args:
-
fileList.append('%s\n' %(dirfile))
-
elif os.path.isdir(dirfile):
-
print "Accessing directory:", dirfile
-
fileList += dir_list2(dirfile, *args)
-
return "".join(fileList)
-
-
if __name__ == '__main__':
-
-
def run_script():
-
dir_name = (os.path.join('C:\\', 'SDS2_7.0', 'macro'))
-
f = dir_list2(dir_name, 'py')
-
print f
One call to print is much faster than iterating on a file list to print each name.
|  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,560
| | | re: Re: extract from zip files..
crashonyou,
Here is another means of compiling a list of file names using os.walk: - import os
-
-
dir_name = (os.path.join('X:/', 'dir1, 'dir2'))
-
-
a = os.walk(dir_name)
-
-
for root, dir, file in os.walk(dir_name):
-
-
print "Root directory: %s" % (root)
-
-
if len(dir) > 0:
-
print "Subdirectories under %s:" % (root)
-
dirList = map(lambda x: '%s\n' % (x), dir)
-
dirStr = "".join(dirList)
-
print dirStr
-
else:
-
print "There are no subdirectories under directory %s" % (root)
-
-
if len(file) > 0:
-
print "Files in directory %s:" % (root)
-
fileList = map(lambda x: '%s\n' % (os.path.join(root, x)), file)
-
fileStr = "".join(fileList)
-
print fileStr
-
else:
-
print "There are no files in directory %s" % (root)
You can use a facimile of the above to create a list of file names to pass to: - import zipfile, os
-
-
def makeArchive(fileList, archive):
-
try:
-
# ZipFile will accept a file name or file object
-
a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
-
for f in fileList:
-
print "archiving file %s" % (f)
-
a.write(f) # Use (f, os.path.basename(f)) if not saving full path
-
a.close()
-
return True
-
except: return False
-
-
if __name__== '__main__':
-
-
arcfile_name = 'H:/TEMP/temsys/zipped_files.zip'
-
-
if makeArchive(fileList, arcfile_name): # fileList == your_file_list
-
print arcfile_name, "was created.\n"
-
# check the new archive file
-
f = zipfile.ZipFile(arcfile_name, 'r')
-
for info in f.infolist():
-
print info.filename, info.date_time, info.file_size, info.compress_size
-
f.close()
-
else:
-
print "There was an error"
HTH :),
BV
| | Newbie | | Join Date: Feb 2007
Posts: 8
| | | re: Re: extract from zip files..
woah,thanks for that one..found it really useful..i'll be modifying it to suit my needs.. :)
| | Member | | Join Date: Jul 2007 Location: Philippines
Posts: 54
| | | re: Re: extract from zip files.. Quote:
Originally Posted by crashonyou woah,thanks for that one..found it really useful..i'll be modifying it to suit my needs.. :)
Sugs,
Buti nalang na post mo ito.Hindi na ako mahihirapang maghanap...heheheh
|  | | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,272 network members.
|