需求:用户输入当前目录下任意文件名,完成对该文件的备份功能(备份文件名为xx[备份]后缀,例如:test[备份].txt)。
思考:
① 接收用户输入的文件名
② 规划备份文件名
③ 备份文件写入数据
代码
# 1、接收用户输入的文件名(要备份的文件名)
oldname = input('请输入要备份的文件名称:')  # python.txt
# 2、规划备份文件名(python[备份].txt)
# 搜索点号
index = oldname.rfind('.')
# 返回文件名和文件后缀
name = oldname[:index]
postfix = oldname[index:]
newname = name + '[备份]' + postfix
# 3、对文件进行备份操作
old_f = open(oldname, 'rb')
new_f = open(newname, 'wb')# 读取源文件内容写入新文件
while True:content = old_f.read(1024)if len(content) == 0:breaknew_f.write(content)
# 4、关闭文件
old_f.close()
new_f.close()