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:
JavaScript
x
8
1
Bread,Condiment1,Condiment2
2
Toast,Butter,Jam,
3
4
#Finds Toast
5
input = Toast
6
#Replaces Jam with Nutella
7
input = Nutella
8
Should then turn into
JavaScript
1
3
1
Bread,Condiment1,Condiment2
2
Toast,Butter,Nutella
3
Advertisement
Answer
I assume you always want to replace the third element of the lines. So I wrote this accordingly
JavaScript
1
13
13
1
with open('example.csv', 'r+', encoding='utf-8') as f:
2
aa = f.readlines()
3
x = input()
4
for k,i in enumerate(aa):
5
if i.startswith(x):
6
y = input()
7
words=i.split(',')
8
words[2] = y
9
aa[k] =','.join(words)
10
f.seek(0)
11
f.write(''.join(aa))
12
f.truncate()
13