Skip to content
Advertisement

Find line via string input and replace specific row in CSV file Python

For an Address Book project, I need to find a specific line in a CSV file via input() IE if a user inputs “Toast” it will find the line with Toast on it, then replace a row on that line such as “Jam” with another input from the user.

Is there a way to do this?

Example:

Bread,Condiment1,Condiment2
Toast,Butter,Jam, 

 #Finds Toast
    input = Toast
 #Replaces Jam with Nutella
    input = Nutella

Should then turn into

Bread,Condiment1,Condiment2
Toast,Butter,Nutella

Advertisement

Answer

I assume you always want to replace the third element of the lines. So I wrote this accordingly

with open('example.csv', 'r+', encoding='utf-8') as f:
    aa = f.readlines()
    x = input()
    for k,i in enumerate(aa):
        if i.startswith(x):
            y = input()
            words=i.split(',')
            words[2] = y
            aa[k] =','.join(words)
    f.seek(0)
    f.write(''.join(aa))
    f.truncate()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement