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
except Exception as msg:
print(msg)
pass
# 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
pass
copyBigFile()
运行结果