您的位置:首页 > 编程语言 > Python开发

Python入门小练习-001-备份文件

2015-03-30 11:18 281 查看
练习适用于LINUX,类Unix系统,一步一个脚印提高Python 。

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命令
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: