Python 解决问题

本文介绍了使用Python解决文件备份问题的过程。从列出需要备份的文件,指定备份目录,到压缩备份文件并以日期命名,再到创建递归目录结构和添加用户注释到文件名,逐步完善了备份程序。在解决问题的过程中,还详细讨论了os.mkdir和os.makedirs的区别与用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 解决问题

提出问题:我想要一个可以为我所有重要的文件创建备份的程序。

解决方案:

  • 需要备份的文件及目录应在一份列表中予以制定
  • 备份要储存一个主备份目录中
  • 备份文件将打包压缩成zip文件
  • zip压缩文件的文件名由当前日期和时间构成

第一版

import os
import time

source = ['/home/chendy/mypython/swa']

target_dir = '/home/chendy/mypython/backup'
target = target_dir + os.sep +\
    time.strftime('%Y%m%d%H%M%S') + '.zip'

if not os.path.exists(target_dir):
    os.mkdir(target_dir)

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('Backup Failed')

编写第一版遇到的问题,总是会遇到os.mkdir的问题,最后上网查了一下关于os.mkdir的解决方案。如下:

  • mkdir(path[,mode])

作用:创建一个目录可以是相对或者是绝对路径,mode的默认模式是0777,如果目录有多级,则创建最后一级如果最后一级目录的上级目录不存在的,则抛出一个OSError。

  • makedirs(path[,mode])

作用:创建递归的目录树,可以是绝对路径也可以是相对路径,mode的默认模式也是0777。如果子目录创建失败或者已经存在,则会抛出一个OSError的异常。

http://bbs.chinaunix.net/thread-1313995-1-1.html详细地址

第二版

import os
import time

source = ['/home/chendy/mypython/swa']

target_dir = '/home/chendy/mypython/backup'

if not os.path.exists(target_dir):
    os.mkdir(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)


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('Backup Failed')

这一版的改进为:使用时间作为文件名,存储在以当前日期为名字的文件夹中。

第三版

import os
import time

source = ['/home/chendy/mypython/swa']

target_dir = '/home/chendy/mypython/backup'

if not os.path.exists(target_dir):
    os.mkdir(target_dir)

today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

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)


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('Backup Failed')

改进:实现将用户提供的注释内容添加到文件名中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值