Python @ DjangoSpin

Archiving Files Using zipfile & tarfile Modules

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

zipfile & tarfile in Python

zipfile & tarfile in Python

The standard libraries zipfile & tarfile facilitate creating and manipulating zip & Unix tar archive files. The tarfile is not limited to Unix, it can be used in Windows also, and is capable of working with bzip2 & gzip files as well. In this article, we will see how to create archives, append to them, extract them with primitive examples. The idea is to get you started, and then you can search further on how to satisfy your requirements.

zipfile & tarfile


Creating new archives: zipfile.ZipFile().write() & tarfile.open().add()

The ZipFile class of zipfile module creates a ZipFile object, which provides us with write() method to create new archive files. The open() function of the tarfile module returns a TarFile object, which provides us with add() method to create archive files.

>>> import zipfile
>>> with zipfile.ZipFile('zipFileOne.zip', mode = 'w') as zF:
	zF.write('fileOne.txt')
	zF.write('fileTwo.txt')
	
>>> import tarfile
>>> with tarfile.open('tarFileOne.tar', mode = 'w') as tF:
	tF.add('fileOne.txt')
	tF.add('fileTwo.txt')

Appending to an archive

In order to append to existing archive files, change the mode in which you are opening archive files to 'a', signalling append mode, rather than 'w'.

>>> with zipfile.ZipFile('zipFileOne.zip', mode = 'a') as zF:
	zF.write('fileThree.txt')
	
>>> with tarfile.open('tarFileOne.tar', mode = 'a') as tF:
	tF.add('fileThree.txt')

Extracting archives: zipfile.ZipFile().extract(), zipfile.ZipFile().extractall() & tarfile.open().extract(), tarfile.open().extractall()

The ZipFile & TarFile objects provide two methods extract() and extractall() to extract contents from archive files. The extract() extracts the mentioned file from the archive whereas extractall() extracts all contents of the archive.

>>> with zipfile.ZipFile('zipFileOne.zip') as zF:
	zF.extract('fileThree.txt')							# returns 'complete_path_to_extracted_file'
	
>>> with zipfile.ZipFile('zipFileOne.zip') as zF:
	zF.extractall()

	

>>> with tarfile.open('tarFileOne.tar') as tF:
	tF.extract('fileThree.txt')
	
>>> with tarfile.open('tarFileOne.tar') as tF:
	tF.extractall()

This article is hardly the complete guide to using zipfile & tarfile standard libraries. It is supposed to give you working snippets to manipulate archive files. For comprehensive examples, follow the links below.


Further Reading


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply