Python小脚本 001 备份文件
2015-04-09 10:32
253 查看
练习适用于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 备份文件脚本
- 实验室的一段Python脚本,根据用户指定路径来备份文件
- python备份文件的脚本
- 备份文件的python脚本(转)
- python 备份文件的小脚本
- 初学python —— 备份文件脚本
- python备份文件以及mysql数据库的脚本代码
- python脚本实例001 - 通过列表内容判断输入输出信息
- 【python】脚本001-文件备份(模板)
- python备份文件的脚本
- Python备份文件脚本
- 使用Python脚本自动修改Windows的IP、网关和DNS设置
- 一个批量更改文件名的Python脚本
- python 脚本作为Windows服务启动
- 删除 python 项目中 .pyc 文件的脚本
- Python、Lua和Ruby——脚本大P.K.
- 强迫自己养成习惯用 python 写一些小脚本
- IronPython脚本调用C#实现的dll库
- 用Python编写自动下载网络小说的脚本
- [Python]HTML转换为TXT的脚本