python - Python:如何将字符串插入 .txt 文件中的特定位置?
问题描述
我有一个 .txt 文件,其中有一个名为id=
如何编写一个脚本来查看该.txt
文件,在 ?id=
之后找到并插入一个字符串=
?
我确实有一个名为字典的单独.py
文件,其中包含一个字典,目的是查找和替换.txt
文件中的某些单词。
我也可以使用这本字典作为查找和插入的一种方式吗?
解决方案
逐行读取文件,如果行有 '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)
推荐阅读
- r - 我可以使用 R 和 ggplot 绘制整个会议期间的与会者人数吗?
- python-3.x - 如何在对象加载失败时生成 AWS SNS 警报以触发 MS Teams 通知?
- c# - Entity Framework Core:从现有的类实例中保存一些属性
- c# - Crystal Report 根据学生登录 ASP.NET MVC 过滤数据
- java - 带有自定义分隔符的 Spring AntPathMatcher 行为异常
- multithreading - 矩阵乘法的多线程矩阵
- python - 我可以在 Google Drive 中的文件上运行脚本吗?
- llvm - x86_64 调用函数时调用约定不正确
- r - 如何在 R 中创建频率表
- reactjs - react-router-dom v6.0.2 中的延迟加载