Connecting Tech Pros Worldwide Help | Site Map

Re: extract from zip files..

Newbie
 
Join Date: Feb 2007
Posts: 8
#1: Feb 23 '07
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..

Expand|Select|Wrap|Line Numbers
  1. def unzip(zip,dst,name):
  2.     zip = zipfile.ZipFile(zip, 'r')    
  3.     os.makedirs(dst+name)
  4.     dst = dst+name
  5.     for filename in zip.namelist():
  6.         bytes = zip.read(filename)
  7.         print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
  8.         file((join(dst,filename)), 'wb').write(zip.read(filename))
  9.     zip.close
  10.  
btw,am using windows xp with py2.4.4..
Expert
 
Join Date: Apr 2006
Posts: 512
#2: Feb 23 '07

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..

Expand|Select|Wrap|Line Numbers
  1. def unzip(zip,dst,name):
  2.     zip = zipfile.ZipFile(zip, 'r')    
  3.     os.makedirs(dst+name)
  4.     dst = dst+name
  5.     for filename in zip.namelist():
  6.         bytes = zip.read(filename)
  7.         print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
  8.         file((join(dst,filename)), 'wb').write(zip.read(filename))
  9.     zip.close
  10.  
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..
Motoma's Avatar
Moderator
 
Join Date: Jan 2007
Location: Maine, USA
Posts: 2,904
#3: Feb 23 '07

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
#4: Feb 23 '07

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 :)
bartonc's Avatar
Moderator
 
Join Date: Sep 2006
Location: Minden, Nevada, USA
Posts: 6,400
#5: Feb 23 '07

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
#6: Feb 24 '07

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.. :)
bartonc's Avatar
Moderator
 
Join Date: Sep 2006
Location: Minden, Nevada, USA
Posts: 6,400
#7: Feb 24 '07

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
#8: Feb 24 '07

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!!


Expand|Select|Wrap|Line Numbers
  1. import zipfile, os, time, datetime, os.path
  2. from zipfile import *
  3. from os import *
  4. from os.path import *
  5. from time import mktime
  6.  
  7. ## Zipfile to be unzipped
  8. zips = 'test.zip'
  9. ## Destination directory
  10. dst = ''
  11. ## Specific folder in destination
  12. name = 'test'
  13.  
  14. zip = zipfile.ZipFile(zips, 'r')
  15. if os.path.exists(dst+name):
  16.     pass
  17. else:
  18.     os.makedirs(dst+name)
  19. dst = dst+name+'/'
  20. for filename in zip.namelist():
  21.     if filename.endswith('/'):
  22.         if os.path.exists(join(abspath(dst),filename)):
  23.             pass
  24.         else:
  25.             os.makedirs(join(abspath(dst),filename))
  26.     else:
  27.         try:
  28.             os.makedirs(normpath((abspath(dst)+'/'+dirname(filename))))
  29.             try:                
  30.                 bytes = zip.read(filename)
  31.                 print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
  32.                 file((join(dst,filename)), 'wb').write(zip.read(filename))
  33.                 accesstime = time.time()
  34.                 timeTuple=(int(zip.getinfo(filename).date_time[0]),\
  35.                            int(zip.getinfo(filename).date_time[1]),\
  36.                            int(zip.getinfo(filename).date_time[2]),\
  37.                            int(zip.getinfo(filename).date_time[3]) ,\
  38.                            int(zip.getinfo(filename).date_time[4]),\
  39.                            int(zip.getinfo(filename).date_time[5]),\
  40.                            int(0),int(0),int(0))
  41.                 modifiedtime = mktime(timeTuple)
  42.                 utime((join(dst,filename)), (accesstime,modifiedtime))
  43.             except IOError:
  44.                 pass
  45.         except:
  46.             if os.path.exists(normpath((abspath(dst)+'/'+dirname(filename)))):
  47.                 try:                
  48.                     bytes = zip.read(filename)
  49.                     print 'Unzipping file:', filename, 'with', len(bytes), 'bytes..'
  50.                     file((join(dst,filename)), 'wb').write(zip.read(filename))
  51.                     accesstime = time.time()
  52.                     timeTuple=(int(zip.getinfo(filename).date_time[0]),\
  53.                                int(zip.getinfo(filename).date_time[1]),\
  54.                                int(zip.getinfo(filename).date_time[2]),\
  55.                                int(zip.getinfo(filename).date_time[3]) ,\
  56.                                int(zip.getinfo(filename).date_time[4]),\
  57.                                int(zip.getinfo(filename).date_time[5]),\
  58.                                int(0),int(0),int(0))
  59.                     modifiedtime = mktime(timeTuple)
  60.                     utime((join(dst,filename)), (accesstime,modifiedtime))
  61.                 except IOError:
  62.                     pass
  63.             else:
  64.                 os.makedirs(normpath((abspath(dst)+'/'+dirname(filename))))
  65. zip.close
  66.  
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#9: Feb 24 '07

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:
Expand|Select|Wrap|Line Numbers
  1. import os
  2.  
  3. # Joined string method
  4.  
  5. def dir_list2(dir_name, *args):
  6.     fileList = []
  7.     for file in os.listdir(dir_name):
  8.         dirfile = os.path.join(dir_name, file)
  9.         if os.path.isfile(dirfile):
  10.             if len(args) == 0:
  11.                 fileList.append('%s\n' %(dirfile))
  12.             else:
  13.                 if os.path.splitext(dirfile)[1][1:] in args:
  14.                     fileList.append('%s\n' %(dirfile))
  15.         elif os.path.isdir(dirfile):
  16.             print "Accessing directory:", dirfile
  17.             fileList += dir_list2(dirfile, *args)
  18.     return "".join(fileList)
  19.  
  20. if __name__ == '__main__':
  21.  
  22.     def run_script():
  23.         dir_name = (os.path.join('C:\\', 'SDS2_7.0', 'macro'))
  24.         f = dir_list2(dir_name, 'py')
  25.         print f
One call to print is much faster than iterating on a file list to print each name.
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#10: Feb 24 '07

re: Re: extract from zip files..


crashonyou,

Here is another means of compiling a list of file names using os.walk:
Expand|Select|Wrap|Line Numbers
  1. import os
  2.  
  3. dir_name = (os.path.join('X:/', 'dir1, 'dir2'))
  4.  
  5. a = os.walk(dir_name)
  6.  
  7. for root, dir, file in os.walk(dir_name):
  8.  
  9.     print "Root directory: %s" % (root)
  10.  
  11.     if len(dir) > 0:
  12.         print "Subdirectories under %s:" % (root)
  13.         dirList = map(lambda x: '%s\n' % (x), dir)
  14.         dirStr = "".join(dirList)
  15.         print dirStr
  16.     else:
  17.         print "There are no subdirectories under directory %s" % (root)
  18.  
  19.     if len(file) > 0:
  20.         print "Files in directory %s:" % (root)
  21.         fileList = map(lambda x: '%s\n' % (os.path.join(root, x)), file)
  22.         fileStr = "".join(fileList)
  23.         print fileStr
  24.     else:
  25.         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:
Expand|Select|Wrap|Line Numbers
  1. import zipfile, os
  2.  
  3. def makeArchive(fileList, archive):
  4.     try:
  5.         # ZipFile will accept a file name or file object
  6.         a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
  7.         for f in fileList:
  8.             print "archiving file %s" % (f)
  9.             a.write(f)    # Use (f, os.path.basename(f)) if not saving full path
  10.         a.close()
  11.         return True
  12.     except: return False
  13.  
  14. if __name__== '__main__':
  15.  
  16.     arcfile_name = 'H:/TEMP/temsys/zipped_files.zip'
  17.  
  18.     if makeArchive(fileList, arcfile_name):    # fileList == your_file_list
  19.         print arcfile_name, "was created.\n"
  20.         # check the new archive file
  21.         f = zipfile.ZipFile(arcfile_name, 'r')
  22.         for info in f.infolist():
  23.             print info.filename, info.date_time, info.file_size, info.compress_size
  24.         f.close()
  25.     else:
  26.         print "There was an error"
HTH :),
BV
Newbie
 
Join Date: Feb 2007
Posts: 8
#11: Feb 28 '07

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
#12: Oct 27 '07

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
Reply


Similar Python bytes