Reputation: 23
Let's say I have a CSV file like this after running the following code:
Andy, 4
Bochr, 2
John, 9
import csv
name = input('name: ')
score = input('score: ')
with open('test.csv', 'a') as f:
a = csv.writer(f)
data = [name, score]
a.writerow(data)
If I was to run that code again and my name is Andy, how would I append my score to the first line instead of starting a new row with the name Andy? For example, let's say I scored 5 again. How would you append it to the first line Andy to look like:
Andy, 4, 5
Bochr, 2
John, 9
Thank you in advance,
Upvotes: 0
Views: 394
Reputation: 3386
Try this:
import csv
name = input('name: ')
score = input('score: ')
rows_list = []
with open('test.csv') as fin:
reader = csv.reader(fin)
for row in reader:
if row[0] == name:
row[1] = score
rows_list.append(row)
with open('test.csv', 'w') as f:
a = csv.writer(f)
data = rows_list
a.writerows(data)
Remember, this assumes you already have a test.csv present
Upvotes: 0
Reputation: 27311
It sounds like you want something that acts more like a database or data-structure than a text file. One solution with a very readable data format is json:
import json
initial_data = {
'Andy': [4],
'Bochr': [2],
'John': [9],
}
with open('test.json', 'w') as fp:
json.dump(initial_data, fp, indent=4)
then your update would be much simpler:
with open('test.json', 'r') as fp:
data = json.load(fp)
data['Andy'].append(5)
and saving the updated data:
with open('test.json', 'w') as fp:
json.dump(initial_data, fp, indent=4)
Upvotes: 1