簡體   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