Python入门小练习-001-备份文件
2015-03-30 11:18
281 查看
练习适用于LINUX,类Unix系统,一步一个脚印提高Python 。
001. 类Unix系统中用zip命令将文件压缩备份至 /temporary/ 目录下:
升级一下:
如果要在 /temporary/ 目录下自动以当天日期的名称生成一个文件夹(if判断不存在文件夹则执行 mkdir 命令),备份的zip文件以当时的时间命名怎么办?并且要在文件名后面加一段注释,例如: /temporary/20150330/123030_add_new_file.zip
运行结果:
001. 类Unix系统中用zip命令将文件压缩备份至 /temporary/ 目录下:
import os import time old_files = ['/home/zhg/aa.py','home/zhg/bb.py'] target_dir = '/temporary/' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr %s %s" % (target,' '.join(old_files)) if os.system(zip_command) == 0: print "Successful backup to",target_dir else: print "error backup failed"
# Linux中上一次命令执行成功会返回0 # ' '.join(sequence)方法见: 字符串方法
升级一下:
如果要在 /temporary/ 目录下自动以当天日期的名称生成一个文件夹(if判断不存在文件夹则执行 mkdir 命令),备份的zip文件以当时的时间命名怎么办?并且要在文件名后面加一段注释,例如: /temporary/20150330/123030_add_new_file.zip
import os import time source_files = ['/home/zhg/temptest/aa.py','/home/zhg/temptest/bb.py'] target_dir = '/temporary/' today = target_dir + time.strftime('%Y%m%d') now = time.strftime('%H%M%S') if not os.path.exists(today): os.mkdir(today) print('Successfully created new directory'),today comment = raw_input('Enter a file comment: ') if len(comment) == 0: target = today + '/' + now + '.zip' else: target = today + '/' + now + '_' + comment.replace(' ','_')+'.zip' zip_command = "zip -qr %s %s" % (target,' '.join(source_files)) if os.system(zip_command) == 0: print('Successfully created zip file',target) else: print('Somthing failed')
运行结果:
zhg@hang:~/testdir$ python backup.py Successfully created new directory /temporary/20150330 Enter a file comment: add new file ('Successfully created zip file', '/temporary/20150330/135040_add_new_file.zip') zhg@hang:~/testdir$ ls /temporary/20150330/ 135040_add_new_file.zip
# comment.replace(' ','_') 把 add new file 的空格换成了下划线 # 关于zip的命令可自行搜索,当然你也可以用tar命令
相关文章推荐
- 【python】脚本001-文件备份(模板)
- python入门-简单的文件备份程序
- 用python脚本定期备份文件
- python 备份文件
- Python备份文件到指定目录下
- python练习程序(读写文件)
- python 网站文件及数据库备份脚本
- 备份网站数据库文件的Python脚本
- python在windows下 完成文件备份的例子
- python练习之读取文件,list,hash
- D-Bus入门(四)——QTDBUS代码,实现ofono代码下的python测试文件activite-context的功能
- 使用Python在Windows下调用Winrar备份文件
- Python应用第一波:文件打包备份
- Python入门练习(二)Viterbi算法
- Python入门练习(一):基于全切分,一元语法模型的汉语分词
- Python入门练习(一):基于全切分,一元语法模型的汉语分词
- ORACLE入门之逻辑备份SH文件
- Python入门的36个例子 之 28 -> Pickle —— 利用文件存储对象
- CCNA入门---备份和恢复IOS以及配置文件
- python备份文件