Creating a program where the user can edit entries in a text file (couriers). However, when writing to the file I get the above error and I’m not too sure as to what exactly is going on here.
Couriers.txt
Ups
Fedex
Couriers.py
CourierList= []
with open('couriers.txt','r+') as file:
for courier in file:
CourierList.append(courier.strip())
#Prints the list with the key value#
for i in range(len(CourierList)):
print (i, end = " ")
print (CourierList[i])
print("")
UserInput = int(input("Which courier (number) would you like to update: "))
ChangeInput = input("What would you like to change it to?: ")
CourierList = CourierList[UserInput]=ChangeInput <--- ERROR IS HERE
file.write(CourierList)
file.close()
I can get the new entry into the list created, but when writing it back to the file I get the issue.
Thank you for nay help!
>Solution :
First of all, you have to replace
CourierList = CourierList[UserInput]=ChangeInput
by
CourierList[UserInput] = ChangeInput
Then you need this to write your updated list to file line by line:
with open('couriers.txt', 'w') as file:
for item in CourierList:
file.write("%s\n" % item)
Full code:
CourierList = []
with open('couriers.txt', 'r+') as file:
for courier in file:
CourierList.append(courier.strip())
for i in range(len(CourierList)):
print(i, end=" ")
print(CourierList[i])
print("")
UserInput = int(input("Which courier (number) would you like to update: "))
ChangeInput = input("What would you like to change it to?: ")
CourierList[UserInput] = ChangeInput
with open('couriers.txt', 'w') as file:
for item in CourierList:
file.write("%s\n" % item)