《python简明教程》中的文件压缩代码整理(修改)

来源:互联网 发布:python pdf2txt 编辑:程序博客网 时间:2024/06/12 00:03

原始资源来源于网络,后续代码与注释为自己修改
版本一,压缩文件,使用日期时间作为文件名

# -*- coding:utf-8 -*-#版本一,压缩文件,使用日期时间作为文件名import osimport time#1 先把需要备份的文件夹,保存进列表source = [r'E:\test'] #注意备份的文件夹目录不能重复#2 设置目标保存文件目录target_dir = 'E:\\'#3 保存为zip格式,规范命名target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'print sourceprint target#4 使用zip command命令,将文件压缩进zip存档zip_command = r"7z.exe a %s %s" % (target, ' '.join(source))#注意,这里的''之间有一个单位的空格符#将7z.exe放在C:\Windows\System32目录下后,再次运行就可以了#运行if os.system(zip_command) == 0:    print '文件已经成功备份至' + targetelse:    print '备份失败...'

版本二,使用日期作为目录名,使用时间作为文件名,使得文件以等级形式存储

# -*- coding:utf-8 -*-#版本二,使用日期作为目录名,使用时间作为文件名,使得文件以等级形式存储import osimport time#1 先把需要备份的文件夹,保存进列表source = [r'E:\test'] #注意备份的文件夹目录不能重复#2 设置目标保存文件目录target_dir = 'E:\\'#3 文件名today = target_dir + time.strftime('%Y%m%d')now = time.strftime('%H%M%S')if not os.path.exists(today): #如果不存在today的文件的话    os.mkdir(today)# 创建一个today名的子目录    print 'Successfully created directory'target = today + os.sep + now + '.zip'# os.sep依据系统不同,自动设为分隔符#4 使用zip command命令,将文件压缩进zip存档zip_command = r"7z.exe a %s %s" % (target, ' '.join(source))#注意,这里的''之间有一个单位的空格符print sourceprint target#将7z.exe放在C:\Windows\System32目录下后,再次运行就可以了#运行if os.system(zip_command) == 0:    print '文件已经成功备份至' + targetelse:    print '备份失败...'

版本三,在版本二的基础上使得在压缩文件名上使用注释

# -*- coding:utf-8 -*-#版本三,在版本二的基础上使得在压缩文件名上使用注释import osimport time#1 先把需要备份的文件夹,保存进列表source = [r'E:\test'] #注意备份的文件夹目录不能重复#2 设置目标保存文件目录target_dir = 'E:\\'#3 文件名today = target_dir + time.strftime('%Y%m%d')now = time.strftime('%H%M%S')#给文件添加注释comment = raw_input('Enter a comment: ')#取得用户的注释if len(comment) == 0:    target = today + os.sep + now + '.zip'#如果注释为0,文件名不变else:    target = today + os.sep + now + '_' + \        comment.replace(' ', '_') + '.zip'#否则加上注释 comment.replace(' ', '_')将注释中的空格变为下划线处理if not os.path.exists(today):     os.mkdir(today)# make a directory    print 'Successfully created directory'#4 使用zip command命令,将文件压缩进zip存档zip_command = r"7z.exe a %s %s" % (target, ' '.join(source))#注意,这里的''之间有一个单位的空格符print sourceprint target#将7z.exe放在C:\Windows\System32目录下后,再次运行就可以了#运行if os.system(zip_command) == 0:    print '文件已经成功备份至' + targetelse:    print '备份失败...'
原创粉丝点击