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

python: 通过脚本实现重要文件的备份

2015-12-15 19:42 846 查看

python: 通过脚本实现重要文件的备份

标签:python 脚本 备份

by 小威威

入门python两周了,我觉得自己应该用python来写一点小东西来玩一玩,所以我就写了一个实现重要文件备份的脚本,现在来展示我的代码。

#!/usr/bin/python3
# Filename: backup_ver3.py

# Function: Help us backup some important document more conveniently
# declare The modules os and time
import os
import time

# source is the document that we want to backup
# today_dir is the path of the new folder
# today is the folder that we want to establish
# now is the name of the zip
source = ['/Users/apple/Desktop/python']
today_dir = '/Users/apple/Desktop/python/'
today = today_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

# Judge whether the folder of time is exist, if not, establish it
if not os.path.exists(today):
os.mkdir(today)
print ('Successful mikdir!')

# The comment we want to add to the backup
string = input('Please enter what you want to note:')

# judge whether the users have entered the comment,if not, carry out the original way, else add the comment to the name of backup
# os.sep represents the seperation of address,because in different system, the seperation is different
if len(string) == 0:
target = today + os.sep + now + '.zip'
else :
target = today + os.sep + now + '_' + \
string.replace(' ', '_') + '.zip'

# The command is the string that excute in terminal
command = 'zip -qr %s %s' % (target, ''.join(source))

# if the backup is success, the system will return 0
if os.system(command) == 0:
print ('Sucessfully backup to', target)
else:
print ('Backup failed')


输出结果:

appledeMacBook-Pro-2:~ apple$ cd Desktop
appledeMacBook-Pro-2:Desktop apple$ cd python
appledeMacBook-Pro-2:python apple$ python3 backup_ver3.py
Please enter what you want to note:important
Sucessfully backup to /Users/apple/Desktop/python/20151215/195936_important.zip


有了这个脚本,当我们要备份文件时,只需要执行脚本就能够实现。这个脚本的优点是:能够较快实现文件的压缩,而且每一天都有对应日期文件夹,文件以时间命名,同时还可以添加自己的注释。换句话说,这个脚本使我们的备份很有条理,倘若我们自己通过软件操作,时间一定大大超过脚本执行时间,所以,这个脚本还是有一定的价值的。它在一定程度上方便了我对重要文件的备份操作。

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: