文件操作练习题

Posted hexiaorui123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件操作练习题相关的知识,希望对你有一定的参考价值。

写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作

def
modify_file(filename, old, new): # 定义函数 import os # 导入文件模块 with open(filename, r, encoding=utf-8) as f_read, open(txt, w, encoding=utf-8)as f_write: # 1、读的模式打开传入的文件,创建新的文件 for line in f_read: # 每一行进行迭代,遍历 if old in line: # 旧内容在 line中 line = line.replace(old, new) # 用新的取代旧的 f_write.write(line) # 新的line 写入‘txt‘文件中 os.remove(filename) # 文件删除旧的文件 os.rename(txt, filename) # 把新文件重新命名为 filename modify_file(xxx_new, alex,seven) # 传入需要修改的文件,旧的内容,新的内容

 



以上是关于文件操作练习题的主要内容,如果未能解决你的问题,请参考以下文章