Python3实现将文件树中所有文件和子目录归档到tar压缩文件的方法

WBOY
Release: 2016-06-06 11:17:14
Original
1234 people have browsed it

本文实例讲述了Python3实现将文件树中所有文件和子目录归档到tar压缩文件的方法。分享给大家供大家参考。具体实现方法如下:

# 这里将一个文件树中的所有文件和子目录归档到一个tar归档文件,然后压缩 
import tarfile, os 
# compression表示压缩算法,gz表示gzip颜色,bz2表示bzip2压缩,
# 空字符串表示不压缩 
# folder_to_backup: 要归档的文件夹 
# dest_folder 表示目标文件夹 
def make_tar(folder_to_backup, dest_folder, compression = 'bz2'):
  # dest_ext 表示扩展名 
  if compression: 
    dest_ext = '.' + compression 
  else: 
    dest_ext = '' 
  arc_name = os.path.basename(folder_to_backup) 
  # dest_name 为目标文件名,dest_path 为目标文件路径 
  dest_name = '%s.tar%s' % (arc_name, dest_ext) 
  dest_path = os.path.join(dest_folder, dest_name) 
  # 压缩方法决定了open的第二个参数是 "w", 或"w:gz", 或"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)
Copy after login

希望本文所述对大家的Python3程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!