Python5:Script

本文介绍了一个用于Windows系统的文件备份程序,程序分为两个版本,通过Python实现文件及目录的自动备份功能,备份文件被压缩并存储为主备份目录下的ZIP或RAR文件。

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

1.Question & Analysis

Q:为所有重要文件穿件备份的程序
  • 需要备份的文件和目录有一个列表指定
  • 备份应该保存在主备份目录中
  • 文件备份成Zip文件
  • Zip存档的日期是当前的日期和时间
  • Windows用户应该使用Info-Zip程序

2.version1.0

#backup_version1.py
import os
import time

#the file and directionaries to be backed up are specified in a list
source = ['F:\\CV\\CV.doc']; #r防止转义

#the backup must be stored in a main backup directory
target_dir = 'F:\\backup\\';

#the files are backed up into a zip file
#the name of the rar archive is the current data and time
target = target_dir + time.strftime('%Y%m%d%H%M%S')+'.rar';
print (target);

#use the rar command to put the files in a zip archive
rar_command = "Rar a %s %s" % (target,' '.join(source))
print (rar_command);

#run the backup
if os.system(rar_command)==0:
	print 'Successful backup to',target
else:
	print'Backup Failed'
Windows下使用Rar命令成功验证,首先确保Windows下C:\Windows\System32目录下有Rar.exe文件。

3.version2.0

修改:创建子目录,以日期命令;创建压缩文件,以时间命名。
import os
import time
source = ['F:\\CV'];
target_dir = 'F:\\Backup\\';

#The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
#The current time is the name of the rar archive
now = time.strftime('%H%M%S');

#Create the subdirectory if it isn't already there
if not os.path.exists(today):
    os.mkdir(today); # make directory
print 'Successfully created directory', today;

#The name of the rar file
target = today + os.sep + now + '.rar';
rar_command = "Rar a %s %s" % (target,' '.join(source));
# Run the backup
if os.system(rar_command) == 0:
    print 'Successful backup to', target;
else:
    print 'Backup FAILED';

两个程序的大部分是相同的。改变的部分主要是使用os.exists函数检验在主备份目录中是否有
以当前日期作为名称的目录。如果没有,我们使用os.mkdir函数创建。
注意os.sep变量的用法——这会根据操作系统给出目录分隔符,即在Linux、Unix下它是'/',在Windows下它是'\\',而在Mac OS下它是':'。使用os.sep而非直接使用字符,会使程序具有移植性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值