The tarfile module, included with Python, provides a set of easy-to-use methods to create and manipulate TAR files. The open(filename [, mode [, fileobj [, bufsize]]]) method must be called with the write mode set to create a new TAR. Table 4.2 shows the different modes available when opening a TAR file.
Once the TAR file has been opened in write mode, files can be added to it using the add(name [,arcname [, recursive]]) method. The add method adds the file or directory specified in name to the archive. The optional arcname argument enables you to specify what name the file should have inside the archive. The recursive argument accepts a Boolean true or false to determine whether or not to recursively add the contents of directories to the archive. Note To open a TAR file for sequential access only, replace the : character in the mode with a | character. The append mode is not available for the sequential access option. import os import tarfile #Create Tar file tFile = tarfile.open("files.tar", 'w') #Add directory contents to tar file files = os.listdir(".") for f in files: tFile.add(f) #List files in tar for f in tFile.getnames(): print "Added %s" % f tFile.close() tar_file.py Added add_zip.py Added del_tree.py Added dir_tree.py Added extract.txt Added extract_tar.py Added file_lines.py Added find_file.py Added get_zip.py Added input.txt Added open_file.py Added output.old Added read_file.py Added read_line.py Added read_words.py Added ren_file.py Added tar_file.py Added write_file.py Output from tar_file.py code |