简体   繁体   中英

How to overwrite a row in csv if new row has same primary key using python

I have CSV like:

Rollno     Name     score
  20      Akshay     33
  21      Sanjay     32

New row which has to be added:

newrow=[21,'sanjay',33]

Resultant CSV be like:

Rollno      Name    score
  20       Akshay    33
  21       Sanjay    33

Instead of list I'd use dict like this.

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

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

#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. 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.

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