首页 > 解决方案 > Python:如何将字符串插入 .txt 文件中的特定位置?

问题描述

我有一个 .txt 文件,其中有一个名为id=

如何编写一个脚本来查看该.txt文件,在 ?id=之后找到并插入一个字符串=

我确实有一个名为字典的单独.py文件,其中包含一个字典,目的是查找和替换.txt文件中的某些单词。

我也可以使用这本字典作为查找和插入的一种方式吗?

标签: python

解决方案


逐行读取文件,如果行有 'id=' 用 str 的内置替换方法替换它并写入新行,否则写入旧行。

with open(path_to_file) as fp:
  with open(path_to_new_file, 'w') as nfp:
    string = "whatever"
      for line in fp: 
        if "id=" in line:
          new_line = line.replace("id=", f"id={string}")
          print(f"replacing {line} with {new_line}")
          nfp.write(new_line)
        else: 
          nfp.write(line) 

推荐阅读