简体   繁体   中英

Python: How to allow user to select line to edit?

I've been trying to load a text file into Python and replace the last word. The text file looks like this:

A1 I'm at the shop with Bill
B3 I'm going to the shop with Sarah
E3 I was at the shop with nobody
F5 I'm at the shop with Cameron

I'd like to allow the user to choose which line to edit. So, they could enter B3 for the second line and then replace the name at the end. I've tried numerous things with it as a function, but I just can't number the lines to be edited.

Use ord(c) function to convert a letter into a number, and use that to choose your line index.

choice = input("Enter the row you would like to change")

if choice.isalpha(): # if they enter 1 or b or C
    choice_num = ord(choice.lower()) - 97
else:
    choice_num = choice

with open('shops.txt') as shoplist:
    lines = shoplist.read().splitlines()
    name = lines[choice_num].split()[-1]
    lines[choice_num] = lines[2].replace(name, "Steve")
    with open ('shops.txt','w') as shoplist:
        for l in lines:
            shoplist.write(l+"\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