python - 如何在特定行或位置编辑文本文件
问题描述
我有一个格式如下的文本文件,我正在尝试编辑/更新文件中的文本。
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)
没有编辑提到的特定位置,而是在最后添加的可能原因是什么。提前致谢。
解决方案
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()
另一个答案中提到的方法一次只获取一行,对其进行编辑并将其写回。不过,您仍然需要谨慎使用该模式。
推荐阅读
- c# - 在 API Gateway 中注册 DbContext
- mantis - 创建 Mantis 票证时插入到 custom_fields
- docker - Jenkins windows docker运行镜像失败,工作目录无效,需要是绝对路径
- c# - UnitOfWork 暴露在服务层。我正确地接近这个吗?
- kubernetes - Kubernetes setup
- r - ggplot 上 Tukey 字母图的各个方面的一致刻字
- boost - 检查 Boost::boost 目标是否存在失败
- python - Pygame 将 28x28 像素缩放为 420x420
- reactjs - 如何在材质 UI 中为每个选项卡创建具有多个标签的自定义选项卡?
- java - 使用java识别和禁用(只读)word文档(.docx)的特定部分