简体   繁体   English

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

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

Alright, I am writing a program so that it change the name of cars.For example, it replaces BMW with the new name I entered, without changing any other details.好的,我正在编写一个程序来更改汽车的名称。例如,它将 BMW 替换为我输入的新名称,而不更改任何其他细节。 The problem is always end up emptying my text, and I know that I am using the write mode.问题总是最终清空我的文本,我知道我正在使用写入模式。 Can anyone tell me how to fix this code谁能告诉我如何修复此代码

here is the format of my text file BMW,2011,Automatic,50000,这是我的文本文件 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)

''' '''

You will want to use open('Cars.txt', 'w') to overwite Cars.txt.您将需要使用open('Cars.txt', 'w')覆盖 Cars.txt。 The 'a' stands for 'append', while the 'w' stands for 'write'. “a”代表“追加”,而“w”代表“写入”。 You are also currently always editing the index [0], while the part of the list where the string to replace resides could be anywhere, There is probably a better implementation for this.您目前还一直在编辑索引 [0],而要替换的字符串所在的列表部分可能在任何地方,对此可能有更好的实现。 but these changes should work + illustrate my point.但是这些更改应该起作用+说明我的观点。

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