Home > Mobile >  How do I replace data that is already existed in txt file --python
How do I replace data that is already existed in txt file --python

Time:06-22

sorry for my bad English I would like to do an edit function for my project however I couldn't save the edited content into the txt file. Is there any advice?

def admin_edit_medic():
    list_of_medicine = []
    with open("medic.txt", "r") as medifile:
        for line in medifile.readlines():
            split = line.split(",")
            list_of_medicine.append(split)
    
    print(list_of_medicine)
    print("\n"*2)
    
    updated_details = []
    data = str(input("Please input details to edit from the list: "))
    edit = str(input("Please input new details to replace: "))
    
    for medicine in list_of_medicine:
        update = medicine.replace(data,edit)
        updated_details.append(update)
        
    print(list_of_medicine)

|txt file content|

Abacavir,20/5/2065,49.5,Treat HIV

Alemtuzumab,31/8/2045,977.9,Cure Leukhimia

CodePudding user response:

The code below should do the trick. I've also taken the privilege of not parsing the CSV file medic.txt manually because: So You Want To Write Your Own CSV code?. The code uses a standard Python module called csv.

import csv

def admin_edit_medic():
    list_of_medicine: list[str] = []
    with open("medic.txt", "r") as medifile:
        csv_reader = csv.reader(medifile)
        for row in csv_reader:
            list_of_medicine.append(row)

    print(list_of_medicine)
    print("\n"*2)

    updated_details = []
    data = str(input("Please input details to edit from the list: "))
    edit = str(input("Please input new details to replace: "))

    for row in list_of_medicine:
        updated_row: list[str] = []
        for item in row:
            update = item.replace(data, edit)
            updated_row  = [update]
        updated_details.append(updated_row)

    print(list_of_medicine)
    print(updated_details)

    with open("medic.txt", "w") as medifile:
        csv_writer = csv.writer(medifile)
        for row in updated_details:
            csv_writer.writerow(row)


if __name__ == '__main__':
  admin_edit_medic()

CodePudding user response:

Here you opened a file in a read-only mode. To change its content, you would need to open it in 'w' mode (to write information to a file). Also, there are a few problems with your code. split returns a list, so you won't be able to use replace method as medicine object. To avoid this and correctly writing to the file, try adding this in the end of your function:

for medicine in list_of_medicine:
    medicine = [edit if elem == data else elem for elem in medicine]
    updated_details.append(medicine)

with open('medic.txt', 'w', encoding='utf-8') as new_file:
    for line in updated_details:
        line = ",".join(line)
        new_file.write(line)
  • Related