【问题标题】:Reading from CSV, updating a value and then re-writing从 CSV 读取,更新一个值,然后重写
【发布时间】:2016-06-27 13:03:27
【问题描述】:

我正在尝试从 csv 文件中读取数据,然后根据用户选择更新字段并将内容(包括修改)写入新的 csv 文件。我已经管理了一切,但我的解决方案只写了修改后的行,而不是其余的文件内容。

csv 文件如下所示:

1001, item1, 0.5, 10
1002, item2, 1.5, 20

这是我尝试的一个例子:

run="yes"
while run=="yes":
    id=input("Enter the id of the product you want to order: ")
    amount=input("Enter the quantity: ")

    reader = csv.reader(open('items.csv', 'r'))
    writer = csv.writer(open('updatedstock.csv','w'))

    for row in reader:
        if id==row[0]:
            name=row[1]
            price=row[2]
            stock=row[3]
            newstock=int(stock)-int(amount)
            writer.writerow([id, name, price, newstock])

    run=input("Do you want to order another item? yes/no ")

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    如果您根据条件匹配 id,则您当前仅写入新文件:

    if id==row[0]:
    

    将其更改为始终写入行:

    run="yes"
    
    while run=="yes":
        id=input("Enter the id of the product you want to order: ")
        amount=input("Enter the quantity: ")
    
        reader = csv.reader(open('items.csv', 'r'))
        writer = csv.writer(open('updatedstock.csv','w'))
    
        for row in reader:
            if id==row[0]:
                name=row[1]
                price=row[2]
                stock=row[3]
                newstock=int(stock)-int(amount)
                writer.writerow([id, name, price, newstock])
            else:
                writer.writerow(row)
    
        run=input("Do you want to order another item? yes/no ")
    

    但是,如果您计划替换许多值,这可能会非常低效,因为每次更改都会读取 csv。最好读入所有要更改的值,然后通过 csv 修改所需的条目。

    更好的是使用其他一些数据结构,例如 SQLite,它在查找和写入方面表现更好。当然,这不会像文件系统中那样易于人类阅读。如果需要,您可以轻松地将 sqlite 数据库输出到 .csv:Export from sqlite to csv using shell script

    【讨论】:

    • 另外,seriously(!) 考虑使用 SQLite! 只要您使用事务(!),这是一种“管理数据文件”的出色且高性能的方式。 SQLite 数据库“单个文件”。不需要外部服务器。而且,SQLite 团队在使其始终如一地提供出色性能方面做得非常出色。
    • 唯一的警告......这是一个非常重要的......是您必须使用事务来实现“惰性写入”。否则,SQLite 将物理验证每次读取和写入,导致它出乎意料地(非常)慢。当事务用于读取写入时,它的表现就像来自炎热地方的有翼哺乳动物。 :-D
    猜你喜欢
    • 1970-01-01
    • 2013-06-14
    • 2023-04-02
    • 2017-01-09
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多