CSV读取器/写入器不会使用新信息Python.3更新.csv

时间:2019-08-28 15:57:09

标签: python python-3.x csv

我的工作Python脚本(不引发任何错误)似乎忽略了if语句,直接进入else语句。它似乎没有检查csv中的特定元素,也没有将该元素写入新的csv中。

一定是天真的编码错误吗?

以前的代码更加复杂,但是从那时起,我将其剥离,以发现问题的症结所在。没有引发任何错误,并且代码完全执行。没有错误意味着我无法完全搜索特定内容。

import csv

    # Print merchant's inventory
    with open('merchant.csv', 'r') as csvfile:
        inventory = csv.reader(csvfile)
        for row in inventory:
            print(', '.join(row))

        choice = input('\n\nWhat would you like to purchase?\n\n')

        # Check to see if entry is actually in the printed list
        if choice in inventory:

            # Write choice into user.csv
            with open('user.csv', 'a') as A:
                inventory = csv.writer(A, delimiter = ',')
                inventory.writerow([choice])

        else:
            print("That's not in my list.")




 merchant.csv

ITEM    PRICE   WEIGHT
----------------------
Item1   20  14
Item2   15  15
Item3   100 1
----------------------

该代码模仿某种商人贸易,显示库存清单(merchant.csv),并让用户从该清单中选择一个项目,然后将其添加到其库存(user.csv)中,该项目开始为空。

user.csv在执行主代码后仍然为空。

新手在这里!感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这应该有效:

import csv

# Print merchant's inventory
with open('merchant.csv', 'r') as csvfile:
    inventory = csv.reader(csvfile)
    items = []
    for row in inventory:
        items.append(row[0])
        print(', '.join(row))

    choice = input('\n\nWhat would you like to purchase?\n\n')

    # Check to see if entry is actually in the printed list
    if choice in items:

        # Write choice into user.csv
        with open('user.csv', 'a') as A:
            inventory = csv.writer(A, delimiter = ',')
            inventory.writerow([choice])

    else:
        print("That's not in my list.")

答案 1 :(得分:0)

使用熊猫的上述替代版本
Skymons答案会创建一个列表,然后可以根据用户的选择进行搜索。
而通过从头开始以DataFrame的形式读取csv,该列就可以作为列表读取。

import csv
import pandas as pd

inv=pd.read_csv("merchant.csv")

choice = input('What would you like to purchase?\n')

if inv['Item'].str.contains(choice).any():
    with open('user.csv', 'a') as A:
            inventory = csv.writer(A, delimiter = ',')
            inventory.writerow([choice])

else:
    print("That's not in my list.")