首页 > 解决方案 > 基于匹配关键字向文本文件添加新文本(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()  

标签: python

解决方案


推荐阅读