今天学了python文件读写,老师布置的作业就是检索文本,对某一关键词进行检索并且替换。

这里用到了文件读写的知识,主要注意的是1.字符集的处理 使用utf-8 2.按行读取,避免文件读取失败

主要的操作流程为打开文件、读文件、写文件、替换。代码如下

infile = open("history_python.txt", "r",encoding='utf-8')  #打开文件
outfile = open("content.txt", "w",encoding='utf-8') # 内容输出
for line in infile:  #按行读文件,可避免文件过大,内存消耗
      outfile.write(line.replace('语言', '编程语言'))#first is old ,second is new
infile.close()    #文件关闭
outfile.close()

运行结果如下:

原文本:

python 文本置换 python文本替换程序_读文件

替换后:

python 文本置换 python文本替换程序_读文件_02