簡體   English   中英

如何更改文本文件中的特定字符串?

[英]How to change a particular string in a text file?

好的,我正在編寫一個程序來更改汽車的名稱。例如,它將 BMW 替換為我輸入的新名稱,而不更改任何其他細節。 問題總是最終清空我的文本,我知道我正在使用寫入模式。 誰能告訴我如何修復此代碼

這是我的文本文件 BMW,2011,Automatic,50000 的格式,

'''

old = input("Old Name: ")
new = input("New Name: ")
result = ""

with open('Cars.txt', 'r') as file:
    var = file.readlines()

for row in var:
    element = row.split(',')
    if old in element:
        element[0] = new
        row = ",".join(element)
        result += row

with open('Cars.txt', 'w') as file:
    Write = file.write(result)

'''

您將需要使用open('Cars.txt', 'w')覆蓋 Cars.txt。 “a”代表“追加”,而“w”代表“寫入”。 您目前還一直在編輯索引 [0],而要替換的字符串所在的列表部分可能在任何地方,對此可能有更好的實現。 但是這些更改應該起作用+說明我的觀點。

old = input("Old Name: ")
new = input("New Name: ")
result = ""

with open('Cars.txt', 'r') as file:
    var = file.readlines()

for row in var:
    element = row.split(',')
    if old in element:
        element[element.index(old)] = new
        row = ",".join(element)
        result += row

with open('Cars.txt', 'w') as file:
    Write = file.write(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM