简体   繁体   中英

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. 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,

'''

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. The 'a' stands for 'append', while the 'w' stands for 'write'. 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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