Python学习笔记——备份文件的脚本

 

opt+cmd+L快捷键可以格式化代码(自动在等号左右加空格,平时手写应保持这样的良好习惯)

第二版: 

使用时间作为文件名,存储在以当前日期为名字的文件夹中,这一文件夹则照常存储在主备份目录下

import os
import time

'''
使用时间作为文件名,存储在以当前日期为名字的文件夹中,这一文件夹则照常存储在主备份目录下
1、先设置备份文件路径,
2、再给出目标文件路径,如果没有目标文件则新建(os.mkdir)一个
3、给目标文件命名(主目录名;年月日)+(子目录名:时间);如果主目录不存在则新建一个
4、zip命令-r选项用来打包
5、运行备份
opt+cmd+L快捷键可以格式化代码
'''
source = ['/Users/zl/Desktop/sql导出']
target_dir = '/Users/zl/Desktop'
if not os.path.exists(target_dir):
    os.mkdir(target_dir)
    print('successfully created directory target_dir')
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

target = today + os.sep + now + '.zip'
if not os.path.exists(today):
    os.mkdir(today)
    print('successfully created directory today', today)
zip_command = 'zip -r {0} {1}'.format(target, ' '.join(source))  # 这里的{0} {1}之间要有空格,否则会报错

print('zip command is:', zip_command)
print('Running:')
if os.system(zip_command) == 0:
    print('Successfully backup to', target)
else:
    print('backup failed')

 

第三版:

将用户的注释内容添加到备份目标的文件名中
# str.replace(ole,new[,max])方法,把字符串中的old(旧字符串)替换成new(新字符串);如果指定第三个参数max,则替换不超过max次
import os
import time

'''
将用户的注释内容添加到备份目标的文件名中
1、待备份文件的路径,以列表形式给出
2、备份目标文件夹路径,以字符串形式给出
3、判断目标文件夹是否存在os.path.exists(),若不存在,新建(os.mkdir())
4、设置目标zip文件名称;主目录名字、子目录名字
5、添加用户注释(用input输入)字符串格式
6、判断注释是否为空,为空则 zip文件名=目标文件夹路径+主目录+子目录;不为空则 zip文件名=目标文件夹路径+主目录+子目录+注释;
7、如果主目录不存在,则新建os.mkdir一个
8、使用zip命令打包
'''
source = ['/Users/zl/Desktop/sql导出']
target_dir = '/Users/zl/Desktop'
if not os.path.exists(target_dir):
    os.mkdir(target_dir)
    print('successfully created directory target_dir')
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

comment = input('the comment is-->')
if len(comment) == 0:
    target = today + os.sep + now + '.zip'  # 注意要在today和now之间加上os.sep分隔符,才能使备份的内容存到子目录下
else:
    target = today + os.sep + now + '_' + comment.replace(' ','_') + '.zip'  # str.replace(ole,new[,max])方法,把字符串中的old(旧字符串)替换成new(新字符串);如果指定第三个参数max,则替换不超过max次

if not os.path.exists(today):
    os.mkdir(today)
    print('successfully created directory today')
zip_command = 'zip -r {0} {1}'.format(target, ' '.join(source))

print('zip command is', zip_command)
print('Running:')
if os.system(zip_command) == 0:
    print('Successfully backup to:', target)
else:
    print('backup failed')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值