源码如下
def copyFile():
# 接收用户输入的文件名
old_File=input('请输入要备份的文件:')
# 构造新的文件名,加上备份后缀
File=old_File.split('.')
new_File=File[0]+'_备份.'+File[1]
try:
# 同时打开需要备份的文件,新文件
with open(old_File,'r',encoding='utf-8') as Old_f,open(new_File,'a',encoding='utf-8') as New_f:
while True:
# 一次读取1024字符,防止内存泄露
Content=Old_f.read(1024)
New_f.write(Content)
# 当读取的内容字符长度小于1024说明已经读取完毕
if len(Content)<1024:
break
except Exception as msg:
print(msg)
copyFile()