简体   繁体   中英

How to read multiple lines from a text file and choose one to edit

I am a university student and have to prepare a lesson in Python to give to a class of year 9's. I have created an address book program which allows them to create an address book and add entries and view the book.

The one part I can't figure out is how to edit entries. You basically have to be able to pick one out of several lines and then type new data which will save over the original line.

When adding entries originally, I take in the name, age, address and city in separate variables and then write them to a text file with commas between them.

I wasn't sure what information to give over just yet as I don't usually use Stack Overflow so if you need any more information or code please just let me know!

Thank you! David

Edit I've added all the code below. It prints to a text file and separates them by commas.

def createAddBook():
f = open("address_book.txt", "w")

def viewAddBook():

f = open("address_book.txt", "r")

contacts = f.read()

print(contacts)
print()

f.close

def addEntry():
addList = []

Name = input("What is the name?" + "\n")
Age = input("What is the age?" + "\n")
Address = input("What is the address?" + "\n")
City = input("What is the city?" + "\n")

addList.append(Name + ", ")
addList.append(Age + ", ")
addList.append(Address + ", ")
addList.append(City + "\n")

f = open("address_book.txt", "a")

for entry in addList:
    f.write(entry)

f.close()



inuse = True
while inuse == True:
choice = input("Do you have an address book? (yes/no)" + "\n")
if choice == "yes":
    choice = input("Would you like to view, add or edit your address book? (view/add/edit)" + "\n")
    if choice == "view":
        viewAddBook()
    elif choice == "edit":
         editEntry()
    elif choice == "add":
        addEntry()

elif choice == "no":
    createAddBook()
    print("Address book has been created!")

    choice = input("Would you like to add an entry to the address book? (yes/no)"  + "\n")
    if choice == "yes":
        addEntry()
    elif choice == "no":
        inuse = False
elif choice == "close":
    break

I understand that you want to create your address book as a CSV file (store one entry per line, and use commas to separate the fields of a given entry). Is that your goal? To manage such a file, the easiest solution is to use the csv module from the standard Python library. Here is a link to the documentation page:

https://docs.python.org/3/library/csv.html#examples

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