Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Editing a text file based on user input error. When the user adds an entry I get the this error – 'str' object does not support item assignment

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading