简体   繁体   中英

How to edit a specific word on a specific line base on user input?

I am working on an Flight ticket reservation system as part of my university project. Use of Modules and Global variable are not allowed. My project consist of flight schedule, which is saved and stored in a .txt file named schedule.txt. It is also stated that I need to code for the admin where they can freely edit the details in flight schedule. Details in flight schedule include: Booking code, Flight number, Airline, From, To and date of departure.

schedule = open("schedule.txt", "w")
schedule.write("\n[100] MH371, MALAYSIAN AIRLINE, KUALA LUMPUR, BEIJING , 19-12-2021, N/A"
               "\n[200] SX849, AIRASIA          , KUALA LUMPUR, BANGKOK , 05-01-2022, N/A"
               "\n[300] MH234, MALAYSIAN AIRLINE, KUALA LUMPUR, LANGKAWI, 03-02-2022, N/A"
               "\n[400] FD709, KOREA AIRLINE    , KUALA LUMPUR, SEOUL   , 29-12-2021, N/A"
               "\n[500] Z1314, CATHAY AIRLINE   , KUALA LUMPUR, TOKYO   , 21-01-2022, N/A"
               "\n[600] HY520, EMIRATES         , KUALA LUMPUR, TAIPEI  , 15-11-2021, N/A"
               "\n[700] TT879, MALINDO AIR      , KUALA LUMPUR, HAWAII  , 08-02-2022, N/A")
schedule = open("schedule.txt", "r")
print(schedule.read())

Initially my code was

with open('schedule.txt') as new_schedule:
  contents = new_schedule.read()

old_data = str(input("Data to edit: "))
new_data = str(input("New data: "))
contents = contents.replace(old_data, new_data)

with open('schedule.txt', 'w') as file:
  schedule.write(contents)

But obviously this code doesn't work as there are recurring data in the txt file such as "KUALA LUMPUR" I tried to implement the enumerate() function but that reads an entire line and I don't know how to just choose to replace 1 word from that line

I think u can use enumerate to read index and string line :

with open("schedule.txt") as fp :
    for i, line in enumerate( fp ):
        if i == 1:
            print (line)

after that split the line with split(',')

temp = line.split(',')

and replace index of line with new one and use

" , ".join(temp)

and replace the line with var temp

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