首页 > 解决方案 > 如何在特定行或位置编辑文本文件

问题描述

我有一个格式如下的文本文件,我正在尝试编辑/更新文件中的文本。

VAR_GROUP
Var1 : DATATYPE1;(描述 Var1)
Var2 : DATATYPE2; (此处要添加的文字)
Var3 : DATATYPE3;(Description Var3)
Var4 : DATATYPE4; (要在此处添加的文字)
END_GROUP

使用 Python 我正在尝试添加某些描述,例如 Var3 和 Var4。使用我编写的代码,逻辑工作正常,但文本被添加到文件的末尾,而不是在所需的位置。

def search_write_in_file(file_name, string_to_search, description):
with open(file_name, 'r+') as file_obj:
    # Read all lines in the file
    for line in file_obj:
        # For each line, check if line contains the string
        line_number += 1
        if (string_to_search in line) and flag_found == 0:
            line = line[:-1]+description+'\n'
            file_obj.write(line)
            flag_found =1

read_obj.close()

电流输出
VAR_GROUP
Var1 : DATATYPE1;(描述 Var)
Var2 : DATATYPE2;
Var3 : DATATYPE3;(描述 Var3)
Var4 : DATATYPE4;
END_GROUP
Var1 : DATATYPE1;(描述 Var1)
Var2 : DATATYPE2;(描述 Var2)
Var3 : DATATYPE3;(描述 Var3)
Var4 : DATATYPE4;(描述 Var4)

没有编辑提到的特定位置,而是在最后添加的可能原因是什么。提前致谢。

标签: pythonpython-3.xfile-writing

解决方案


r+您已在模式下打开文件。写入文件需要w+a+模式。尝试这个:

def search_write_in_file(file_name, string_to_search, description):
 lines=[]
 with open(file_name, 'r+') as file_obj:
     # Read all lines in the file
     lines = file_obj.readlines()
 # Make the changes
 for idx in range(len(lines)):
     line = lines[idx]
     # For each line, check if line contains the string
     if (string_to_search in line) and flag_found == 0:
         line = line[:-1]+description+'\n'
         lines[idx]=line
         flag_found =1
 # w+ mode truncates the content and then writes the content back again
 with open(file_name, 'w+') as file_obj:
    file_obj.writelines(line)

或者,您可以使用seek()另一个答案中提到的方法一次只获取一行,对其进行编辑并将其写回。不过,您仍然需要谨慎使用该模式。


推荐阅读