我有一个.txt文件,我想在其中用字符串替换特定的行(第3行)。我不想使用简单的file.replace(targetString,newString),因为我在文件中有多个targetString,并且他们所处的订单是未知的。我知道我要替换的字符串总是在第3行,而且它是第3行的唯一内容。
目前我的代码看起来像这样,我编程很糟糕,所以我很感激你能想到的最简单的答案
with open("LAB5INFO.txt", "r+") as file:
content = file.read()
file.seek(0)
file.truncate()
file.write(content.replace(<<LINE3>>, string))
答案 0 :(得分:1)
我想?
with open("LAB5INFO.txt", "rb") as file:
lines = file.readlines()
lines[2].replace("old","new")
with open("LAB5INFO.txt", "wb") as file:
file.write("\n".join(lines)
答案 1 :(得分:0)
借鉴其他答案,但在这里我们不需要知道原始行的内容
with open("LAB5INFO.txt", "rb") as file:lines = file.readlines()
lines[2]="new third line"
with open("LAB5INFO.txt", "wb") as file: file.write("\n".join(lines))