繁体   English   中英

用字符串替换文件行

[英]Replacing file line with a string

我有一个.txt文件,其中我想用字符串替换特定行(第3行)。 我不想使用简单的file.replace(targetString,newString),因为我在文件中有多个targetString,并且它们所在的顺序是未知的。 我确实知道我要替换的字符串始终在第三行,这是第三行唯一的内容。

目前,我的代码看起来像这样,我在编程方面很糟糕,因此,我希望您能想到最简单的答案

with open("LAB5INFO.txt", "r+") as file:
    content = file.read()
    file.seek(0)
    file.truncate()
    file.write(content.replace(<<LINE3>>, string))

我猜?

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)

从其他答案中借用,但是这里我们不需要知道原始行的内容

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM