Working with a Zip File object

ZipFile instances are similar to file objects. They have these methods:

• close() and read(): Work like the file() object methods of the same names (see Chapter 17).

• getinfo(): Takes a string specifying the name of an item in the archive and returns a Zipinfo() object containing information about the item.

• <zipfile.ZipInfo instance at 0x79fa8>

One way to see the attributes of the Zipinfo() object is to use the dir() function. The following example looks at the contents of a Zipinfo() object called myinfo and then looks at its file size:

['CRC', 'FileHeader', '_doc_', '_init_', '_module_',

'comment',

'compress size', 'compress type', 'create system', 'create version',

'date time', 'external attr', 'extra', 'extract version', 'file_offset',

'file size', 'filename', 'flag bits', 'header offset', 'internal attr',

'orig filename', 'reserved', 'volume'] >>> myinfo.file size 422 0L "

• infolist(): Returns a list of Zipinfo() objects for all items in the order they're stored in the archive.

• namelist(): Returns a list of strings—the names of the items in the archive—like so:

• ['copyy.py', 'helloworld.py', 'myspider.py', 'pagecount.py', 'x']

• printdir(): Lists the items in the archive to sys.stdout.

>>> myz.printdir()

File Name

Modified

Size

copyy.py

2006-

03-07

16

56

54

4220

helloworld.py

2005-

07-05

15

01

: 2 8

22

myspider.py

2005-

11-06

21

:29:

02

4220

pagecount.py

2005-

10-10

15

01

10

367

x

2006-

02-24

13

49

46

0

• testzip(): Examines the checksums (CRCs) of all the items in the archive. Returns as a string the name of the first bad file detected; if all files are good, returns None.

• write(): Takes as an argument a string specifying a pathname and writes the specified file to the archive.

The archive must be open for writing or appending. write() takes two optional arguments:

o arcname, a string specifying the name for the file in the archive (it defaults to the filename) o A compression type, either zip_stored or zip_deflated

This example writes the file 'helloworld.py' to the archive and stores it with the name 'foo':

myz.write('MyDir/helloworld.py', arcname='foo')

• writestr(): Writes a data string to the archive. The archive must be opened with mode 'w' or 'a' . Takes two arguments:

o A string specifying the name that the written data string will have in the archive (or a zipInfo() instance with at least a filename, a date, and a time)

o A string containing the data to store

The zipFile() instance has a data attribute, debug, which specifies the level of debug output to print to sys.stdout. The options range from 0 (no output) to 3 (the most output). The default is 0.

Was this article helpful?

0 0

Post a comment