This example describes how Python3 implements the archive of all files and subdirectories in the file tree to a tar compressed file. Share to everyone for your reference. The implementation method is as follows:
# Archive all files and subdirectories in a file tree to a tar archive file, then compress import tarfile, OS # compression represents the compression algorithm, GZ represents the gzip color, bz2 represents bzip2 compression, # empty string means no compression # Folder_to_backup: Folder to archive # Dest_folder indicates target folder def make_tar (Folder_to_backup, dest_folder, compression = ' bz2 '): # D Est_ext represents the extension if compression: dest_ext = '. ' + compression else: dest_ext = ' arc_name = Os.path.basename (Folder_to_backup) # dest_name is the target filename, Dest_path is the destination file path dest_name = '%s.tar%s '% (Arc_name, Dest_ext) Dest_path = Os.path.join (Dest_folder, Dest_name) # The compression method determines whether the second parameter of Open is "w", or "w:gz", or "w:bz2 " If compression: dest_cmp = ': ' + compression else: dest_cmp = ' out = tarfile. Tarfile.open (Dest_path, ' W ' + dest_cmp) out.add (Folder_to_backup, Arc_name) out.close () return dest_ Path Dest_path = Make_tar (' d:/8 file_system ', ' d:/') print (Dest_path)
It is hoped that this article is helpful to everyone's Python3 program design.