[英]How to replace text in a file using Python
我想讀取一個包含多行切換命令的大文件,然后啟動一個包含相同文本命令列表的新文本文件,但只用所需的新文本替換幾個字符或幾行文本。
我還想有條件,這意味着如果存在一個指定的文本行,那么我希望將所需的文本替換為新文件中的位置。
我正在使用 Visual Studio 代碼
所以你想要這樣的東西:
output = ""
original_file = ()
with open("file.txt", "r") as file:
original_file = file.readlines()
for line in original_file:
for word in line:
if word == "#condition":
output += "#new value"
elif word == "#condition2":
output += "#new value2"
else:
output += word
with open("file.txt", "w") as file:
file.write(output)
順便說一下,我還沒有運行代碼,所以如果有任何錯誤,請告訴我。
所以這里有一個簡短的例子:
with open("data.txt","r") as fin:
with open("output2.txt","w") as fout:
for aline in fin:
new_data = aline
if new_data.startswith("some data"):
new_data = "replacement=string"
elif "coffeebreak" in new_data:
new_data = "coffee is schedualed at 10 on the 15th"
fout.write(new_data+"\n") # You would want to end the line with a linebreak.
“data.txt”的內容:
some data we are logging
some data we are logging
we are having coffeebreak sometime soon
some data we are logging
something about the brown fox
Output 在我們的第二個文件“output2.txt”中:
replacement=string
replacement=string
coffee is schedualed at 10 on the 15th
replacement=string
something about the brown fox
使用with
有很多好處,例如之后無需關閉文件。
希望這對你來說很好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.