python如何备份保存重要文件?

编程入门 行业动态 更新时间:2024-10-27 14:32:07

python如何备份保存<a href=https://www.elefans.com/category/jswz/34/1669372.html style=重要文件?"/>

python如何备份保存重要文件?

工作两年半,最近因为工作需要开始学习些python脚本,这里是一个备份自己学习python代码的程序:
脚本名称:backup.py

import os
import time
# 1. 需要备份的路径
source = '/data00/python_test/2.10'# 2. 备份文件存放路径
target_dir = '/data00/python_test/backup'# 3. 判断 target_dir 目录是否存在,不存在则创建目录
if not os.path.exists(target_dir):os.mkdir(target_dir)# 4. 在 target_dir 目录下创建时间目录,保存备份文件
today_dir = target_dir + os.sep + time.strftime('%Y%m%d')# 5. 判断 target_dir 目录是否存在,不存在则创建目录
if not os.path.exists(today_dir):os.mkdir(today_dir)# 6. 以当前时间保存为备份文件 tar.gz 的名称
new = time.strftime('%H%M%S')# 7. 给打包文件命名
target = today_dir + os.sep + new + '.tar.gz'# 8. 使用 tar 命令打包备份文件以 tar.gz 结尾
tar_command = 'tar -zcPf {0} {1}'.format(target,source)# 9. 运行备份程序
print('tar command is:')
print(tar_command)
print('Running:')
if os.system(tar_command) == 0:print('Successful backup to', target)
else:print('Backup FAILED')

执行结果如下:

# python3 backup.py 
tar command is:
tar -zcPf /data00/python_test/backup/20210222/200728.tar.gz /data00/python_test/2.10
Running:
Successful backup to /data00/python_test/backup/20210222/200728.tar.gz

更多推荐

python如何备份保存重要文件?

本文发布于:2023-07-28 21:52:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重要文件   备份   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!