python创建文件备份的脚本

yipeiwu_com5年前Python基础

制作文件备份

打开原文件

old_f_name = input(“请输入备份的文件路径:”) 
old_f = open(old_f_name, “r”)

打开新文件

new_f_name = “[复件]” + old_f_name 
 123.txt -> 123[复件].txt 123 + “[复件]” + .txt 
 index = old_f_name.rfind(“.”) # 获取.对应的后缀 
if index >= 0: # 如果有后缀 
new_f_name = old_f_name[:index] + “[复件]” + old_f_name[index:] 
 else: # 如果没有后缀 
new_f_name = old_f_name + “[复件]” 
new_f = open(new_f_name, “w”)

读取原文件内容

content = old_f.read()

写入到新文件中

new_f.write(content)

关闭原文件

old_f.close()

关闭新文件

new_f.close()

补充:下面看下python文件备份脚本

import os
import time
source = ['D:\\MyDrivers\hotfix']  #这里可以用自然字符串表示r',因为windows下的分隔符
与python的有冲突,所以需要转义字符\
# 2. 备份文件到目标路径
target_dir = 'F:\\DMDownLoad\\' #这里的末尾一定不要丢分隔符,否者创建的文件会在F:目录下,
而不会在DMDownload目录下
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d') #time.strftime表示对当前时间的调用,括号内为参数设定
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment -->')
if len(comment)==0: 
  target = today+os.sep+now+'.zip' 
#os.sep表示目录符号,windows下是\\,linux下是/,mac下是:,这里为了保证移植性,
所以os.sep会根据系统给出分隔符
else:
  target = today+os.sep+now+'_'+\
       comment.replace(' ','_')+'.zip'
  # Notice the backslash!
# 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)
# 5. 用winrar的rar命令压缩文件,但首先要安装有winrar且设置winrar到环境变量的路径path中
zip_command = "rar a %s %s" %(target,''.join(source))
#这行命令之前的所有target  、target_dir、today这些都是字符串,只有在
这个命令和os.makedir中才是真正的表示路径
# Run the backup
#设置winrar到path环境中,这里已经手动添加了,如果没有去掉#号
#os.system('set Path=%Path%;C:\Program Files\WinRAR')
if os.system(zip_command)==0:
  print'Successful backup to', target
else:
  print'Backup FAILED'

总结

以上所述是小编给大家介绍的python创建文件备份的脚本,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python Pywavelet 小波阈值实例

小波应用比较广泛,近期想使用其去噪。由于网上都是matlib实现,故记下一下Python的使用 Pywavelet  Denoising 小波去噪  # -*-...

Python 元组拆包示例(Tuple Unpacking)

1.元组? 元组的特点: 相当于不可变得列表; 可用于没有字段名的记录。 pythn里的元组就相当于C语言里的数组,是不可变的,但是也可以容纳不同类型的元素,也是容器的一种。 >...

Python列表(list)、字典(dict)、字符串(string)基本操作小结

创建列表 复制代码 代码如下: sample_list = ['a',1,('a','b')] Python 列表操作 复制代码 代码如下: sample_list = ['a','b...

Python机器学习之决策树算法

Python机器学习之决策树算法

一、决策树原理 决策树是用样本的属性作为结点,用属性的取值作为分支的树结构。 决策树的根结点是所有样本中信息量最大的属性。树的中间结点是该结点为根的子树所包含的样本子集中信息量最大的属...

基于MTCNN/TensorFlow实现人脸检测

基于MTCNN/TensorFlow实现人脸检测

人脸检测方法有许多,比如opencv自带的人脸Haar特征分类器和dlib人脸检测方法等。对于opencv的人脸检测方法,有点是简单,快速;存在的问题是人脸检测效果不好。正面/垂直/光线...