简体   繁体   中英

Rewriting Certain parts of a text file (dynamically)

I have a text file like this

A,OXXX#XXXX#XXOO
B,OOXX#XXXX#XXOO
C,OXXX#XXXO#OXXO
D,OOXX#XXXX#XXOO
E,OOOX#OXXO#XXOO
F,##XX#OXXX#XO##

Its something like a movie cinema Where O is available seats, X is unavailable seats and # is a wall

bookSeat = input('Enter seats to book: ').split(',')
    for booking in bookSeat:
        bookRow = booking[0]
        bookColumn = booking[1:]
        availableSeats = seatingPlan[bookRow][int(bookColumn)-1]
            if availableSeats == 'O':
                f = open('Monkey Goes East-202209081430.txt','w')
                #idk whats the next step
            elif availableSeats == 'X':
                print("Seats are already booked!')
            elif availableSeats == '#':
                print('These seats are unavailable')

So if i input A1,B14, it will update the text file into

A,**X**XXX#XXXX#XXOO
B,OOXX#XXXX#XXO**X**
C,OXXX#XXXO#OXXO
D,OOXX#XXXX#XXOO
E,OOOX#OXXO#XXOO
F,##XX#OXXX#XO##

Bolded to show its been change

please help

assuming seatingPlan is a python dict like {'A': ['X','#','O', ...]} and assuming you can modify seatingPlan you could do something along the lines of:

this is pseudo-code. i did not test it.

bookSeat = input('Enter seats to book: ').split(',')

for booking in bookSeat:
    bookRow = booking[0]
    bookColumn = booking[1:]
    availableSeats = seatingPlan[bookRow][int(bookColumn)-1]
    
    if availableSeats == 'O':
        seatingPlan[bookRow][int(bookColumn)-1] = 'X'
    elif availableSeats == 'X':
        print('Seats are already booked!')
    elif availableSeats == '#':
        print('These seats are unavailable')
    # further checking logic ....

with open('Monkey Goes East-202209081430.txt','w') as f:
    for rowCode in sorted(seatingPlan.keys()):
        f.write(rowCode + ',' + "".join(seatingPlan[rowCode]) + '\n')

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