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()
如果文件太大,如超过1-2个g,这个代码就不太合适了。我们的内存是不够的。
如果处理超大文件,一次性将全部内容读取到内存地址是不合适的,接下来进行代码修改。
def copyFile():
# 接收用户输入的文件名
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)
copyFile()