[英]How to overwrite a row in csv if new row has same primary key using python
I have CSV like:我有 CSV 像:
Rollno Name score
20 Akshay 33
21 Sanjay 32
New row which has to be added:必须添加的新行:
newrow=[21,'sanjay',33]
Resultant CSV be like:结果 CSV 就像:
Rollno Name score
20 Akshay 33
21 Sanjay 33
Instead of list I'd use dict like this.而不是 list 我会像这样使用 dict 。
d = {
20: ["Ashay", 33],
21: ["Sanjay", 32]
}
And when updating而且更新的时候
d[21] = ["Sanjay", 33]
This will do exactly what you need.这将完全满足您的需求。
If you can select how to save this to disk I'd use pickle
如果可以 select 如何将其保存到磁盘我会使用
pickle
import pickle
#loading
d = pickle.load(file("filename.pickle"))
#saving
pickle.dump(d,file("filename.pickle","w"))
If you need to parse CSV-file (semicolon as a delimiter here and Unix-style line change (\n)) it can be done like this如果您需要解析 CSV 文件(此处以分号作为分隔符和 Unix 风格的换行符 (\n)),可以这样做
#loading
d = {}
for row in file("filename.csv").readlines():
row=row.split(";")
d[int(row[0])] = [row[1],int(row[2])]
#saving
l = []
for x in d:
l.append(";".join(x,str(d[x][0]),str(d[x][1])))
file("filename.csv","w").write("\n".join(l))
You could do something like this:你可以这样做:
import csv
with open('scores.csv', newline='') as f:
reader = csv.reader(f)
row_dict = {int(row[0]): row for row in reader}
while True:
print(row_dict)
raw = input('(id) name score? ')
if raw in 'Qq':
break
new_row = [x.strip() for x in raw.split()]
if len(new_row) == 3:
# id provided, so overwrite existing row
# or create a new one
row_dict[int(new_row[0])] = new_row
else:
# No id provided
new_id = max(row_dict) + 1
new_row.insert(0, new_id)
row_dict[new_id] = new_row
with open('scores.csv', 'w', newline='') as f:
writer = csv.writer(f)
for _, v in sorted(row_dict.items()):
writer.writerow(v)
The idea is to read the file and create a dictionary from the rows, keyed on the primary key or id.这个想法是读取文件并从行中创建一个字典,以主键或 id 为键。 New entries for the file are added to the dict.
文件的新条目被添加到字典中。 If the new entry includes a primary key the existing row will be overwritten or a new row created if the key does not exist.
如果新条目包含主键,则现有行将被覆盖,如果主键不存在,则会创建新行。 If no primary key is provided a new key is computed.
如果没有提供主键,则计算新键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.