Reputation: 1
My working Python script (throws no errors) ignores the if statement, it seems, moving straight to the else statement. It does not seem to check my csv for a specific element, nor does it write that element to a new csv.
Must be a naive coding mistake?
The code used to be more complicated, but I have since stripped it down to discover this crux of the problem. No errors are being thrown, and the code executes completely. No errors means I can't exactly search for something specific.
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
----------------------
The code imitates a merchant trade of sorts, displaying a list of inventory (merchant.csv) and letting the user choose an item from that list, adding it to their inventory (user.csv), which begins empty.
user.csv remains empty through execution of main code.
Newbie here! Thanks for the help.
Upvotes: 0
Views: 54
Reputation: 405
Alternative version to above using pandas
Skymons answer creates a list which is then searched by the user choice.
Whereas by reading the csv in as a DataFrame from the start the column can already be read as a list.
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.")
Upvotes: 0
Reputation: 870
This should work:
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.")
Upvotes: 1