python - 写入文本文件中的特定行

时间:2016-04-11 15:06:37

标签: python file line

我有一个包含以下内容的文本文件:

$('#delete_pref').html(iNewValue);

在python中,我如何搜索一行并写入它?

例如,我想写入以"名称2"

开头的行
name 1,
name 2,
name 3,
...

任何帮助将不胜感激!

1 个答案:

答案 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)

Reference no 1 Reference no 2