我有一个包含以下内容的文本文件:
$('#delete_pref').html(iNewValue);
在python中,我如何搜索一行并写入它?
例如,我想写入以"名称2"
开头的行name 1,
name 2,
name 3,
...
任何帮助将不胜感激!
答案 0 :(得分:0)
示例代码:
string_to_check = "name 2"
string_to_add = "name 1,"
with open("test.txt", 'r+') as file_to_write:
lines = file_to_write.readlines()
file_to_write.seek(0)
file_to_write.truncate()
for line in lines:
if line.startswith(string_to_check):
line = line.rstrip("\n") + string_to_add + "\n"
file_to_write.write(line)