简体   繁体   中英

Appending to a line in a CSV file

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,

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM