Python备份文件代码实现

学习ing…
(书本上源代码)
本代码函数与变量的解释:
1、len()用来检查用户输入字符的长度,同时来确定用户是否输入字符。当字符等于0时,说明用户没有输入字符。
2、os.sep变量-它将根据你的炒作系统个给出响应的分隔符,在Unix ‘/’、在windows中‘\’、在macOS 中‘:’。注意使用os.sep而非直接使用这些字符有助于使我们的程序变得可移植,从而可以在上述这些系统中都能正常工作。
3.time.strftime()行数遵循某些格式,将%Y将被替换程带有具体世纪的年份等。
4.zip命令:-r 指定zip命令应该递归的对目录进行工作,包括所有的子文件夹与其中的文件

#  coding= utf-8

import os
import time

# 1、需要备份的文件与目录将被指定在一个列表中
source = ['C:\\Users\\Administrator\\Desktop\\a\\b\\c']


# 2、备份文件建必须存储在一个主备份目录中
target_dir = 'C:\\Users\\Administrator\\Desktop\\a\\b\\c\\backup'


# 如果目标目录不存在就,则进行创建
if not os.path.exists(target_dir):
    os.mkdir(target_dir)

# 3、备份文件将打包压缩成zip文件
# 4、将当前日期作为主备份目标下的子目录名称
today = target_dir + os.sep + time.strftime('%Y%m%d')

# 将当前时间作为zip文件的文件名
now = time.strftime('%H%M%S')

# 添加一个来自用户的注释以创建zip文件的文件名
comment = input('Enter a comment -->')
# 检查是否有评论键入
if len(comment) == 0:
    target = today + os.sep +  now + '.zip'
else:
    target = today + os.sep + now + '_' + \
             comment.replace('', '_') + '.zip'
# 如果子目录尚不存在则创建一个
if not os.path.exists(today):
    os.mkdir(today)
    print('Successfully created directory',today)

# 5、我们使用zip命令将文件打包成zip格式
zip_command = 'zip -r {0} {1}'.format(target, ''.join(source))

# 运行备份
print('zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
    print('Successful backup to',target)
else:
    print('bacup FATLED')


猜你喜欢

转载自blog.csdn.net/My_CODEart/article/details/103457601