#文件备份
def copyFile():
#接收文件名
old_file=input(‘输入要备份的文件名:’)
file_list=old_file.split(’.’)
#构造新文件名.加上备份后缀
new_file=file_list[0]+’_备份’+file_list[1]
old_f=open(old_file,‘r’)#打开需要备份的文件
new_f=open(new_file,‘w’)#以写的模式打开这个文件,没有就创建
content=old_f.read()#讲文件内容读取出来
new_f.write(content)#将读取到的文件写入到备份文件中
old_f.close() #关闭旧文件
new_f.close()#关闭新文件
pass
copyFile()
#优化
def copyBigFile():
#接收文件名
old_file=input(‘输入要备份的文件名:’)
file_list=old_file.split(’.’)
#构造新文件名.加上备份后缀
new_file=file_list[0]+’_备份’+file_list[1]
try:
with open(old_file,‘r’) as old_f,open(new_file,‘w’)as new_f:
while True:
content=old_f.read(1024)#一次性读取1024字符
new_f.write(content)
if len(content)<1024:#判断读取的长度
break
pass
pass
pass
except Exception as msg:
print(msg)
pass
copyBigFile()
该博客介绍了两种文件备份方法,包括简单文件复制和优化的大文件复制。优化的复制方法使用了缓冲区读取,提高效率并减少了内存占用。通过输入文件名,程序能够创建带有备份后缀的新文件,实现文件备份功能。

被折叠的 条评论
为什么被折叠?



