温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python如何创建文件备份的脚本

发布时间:2021-04-26 14:16:30 来源:亿速云 阅读:168 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关python如何创建文件备份的脚本的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

python可以做什么

Python是一种编程语言,内置了许多有效的工具,Python几乎无所不能,该语言通俗易懂、容易入门、功能强大,在许多领域中都有广泛的应用,例如最热门的大数据分析,人工智能,Web开发等。

制作文件备份

打开原文件

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如何创建文件备份的脚本”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI