[英]Appending to a line in a CSV file
假設運行以下代碼后,我有一個這樣的CSV文件:
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)
如果我要再次運行該代碼並且我的名字叫Andy,我該如何將分數添加到第一行而不是用Andy開頭新行? 例如,假設我再次得分5。 您如何將其附加到第一行Andy上,如下所示:
Andy, 4, 5
Bochr, 2
John, 9
先感謝您,
聽起來您想要的是某種行為更像數據庫或數據結構而不是文本文件的行為。 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)
那么您的更新會簡單得多:
with open('test.json', 'r') as fp:
data = json.load(fp)
data['Andy'].append(5)
並保存更新的數據:
with open('test.json', 'w') as fp:
json.dump(initial_data, fp, indent=4)
嘗試這個:
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)
請記住,這是假設您已經有一個test.csv
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.