python - 基于匹配关键字向文本文件添加新文本(Python)
问题描述
我想通读一个文本文件,直到遇到一个特定的关键字。
在该关键字之后,是一列名称 + 值以“/”结尾的行。
我想在名称列之后写一个新关键字(它以带有'/'的单行/行结尾)。如果一个或多个名称与我在字典中的名称匹配 - 用字典中的相应值写入名称并以 / 结尾。
写完所有匹配的名称后,它应该在下一行以“/”结尾,就像前面的关键字一样。
文本文件中有数百个关键字出现,因此每次到达关键字时都应在关键字下方添加此新关键字+信息。但是添加的名称和值取决于哪些名称与关键字下的名称匹配。
文本文件结构:
关键词
A_1 10 /
A_2 100 /
/
想在下面添加这个:
关键字2
A_1 62 /
/
基于 input_dict = {A_1:62}
在实际情况下,在 KEYWORD1 和 input_dict 中指定了更多名称。
没有奏效的实施思路:
with open('filename', 'r+') as f:
for line in f:
if line.startswith('KEYWORD'):
for line in f: #starts at keyword
for key in input_list:
if line[0] == key:
#add key value pair from input_list to temporary dictionary.
elif line[0] == '/'
break
#write to file: newline, then key-value from temp-list ending with '/', then newline etc. Should end with a single line of '/'
#continue looping through lines until next instance of keyword is found.
f.close()
解决方案
推荐阅读
- c# - ASP.NET Core 2.x 中间件的自定义依赖注入解析器?
- angular - ng-packagr cssUrl 不在衬里样式或模板中
- jquery - jQuery 切换类让我很难过
- java - 您可以为每个线程(用于测试)创建一个不同的 Hibernate 内存数据库吗?
- highcharts - 在下载的 Highcharts 副本上,在获得许可之前是否禁用自定义?
- html - 为什么
有一个奇怪的黑色顶部边框? - cypress - Cypress.io中如何使用task方法传递数据库连接Url、端口、用户名和密码?
- javascript - 如何在 Ruby On Rails 中自动完成表单域
- python-3.x - 来自带有进程的线程的双端队列
- angular - 无法以反应角度形式定义表单组