简体   繁体   English

如果新行使用 python 具有相同的主键,如何覆盖 csv 中的一行

[英]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.

相关问题 使用Python 2.7在一行中查找字符串以覆盖CSV的这一行 - Finding string in row to overwrite this row of CSV using Python 2.7 Python:当一个键有多个值时,如何将字典写入csv文件,每个键是一个新行,但每个值是一个新列? - Python: How to write dictionary to csv file when one key has multiple values, each key is a new row, but each value is a new column? 使用 python,如何将新项目写入 CSV 文件中的新行 - Using python, how to write new item into a new row in a CSV file SQLAlchemy:如何在具有IDENTITY主键列的Sybase数据库表中插入新行? - Sqlalchemy: How to insert a new row into a Sybase database table which has an IDENTITY primary key column? Python 3, Pandas csv 行具有嵌套在某些字段中的键/值。 如何将其压平成一排宽 - Python 3, Pandas csv row that has key/values nested in some of the fields. How to flatten this into one wide row 如何使用 Python panda 在 csv 中添加新行 - How to add new row in csv using Python panda 如何使用python将同一行中的字符串和数组保存到csv中? - How to save string and array in the same row into csv by using python? 如何在python中将标题行复制到新的csv - How to copy header row to new csv in python 用 Python 中上一行的内容覆盖 csv 文件中一行的内容 - Overwrite contents of a row in a csv file with contents from the row above in Python Python csv writer/重写/覆盖一行或删除所有行并添加新行 - Python csv writer / rewrite /overwrite a row or delete all the rows and add a new one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM