[英]Editing a CSV file in python based on an input
I am to create a program that collects data from a csv file, in which is stored item names and stock. 我要创建一个从csv文件收集数据的程序,该文件中存储了项目名称和库存。 I would like to display to the user how much of, for example apple, is in stock.
我想向用户显示库存中有多少苹果。
Item # Item name Item stock Item price
12345670 Apple 20 0.70
What would you like to buy?: 12345670
How much would you like to buy?: 10
And what I'm trying to do is edit the CSV file to display the new figure of 10
since there are 20 apples and the user purchases 10. I have tried various methods but they all give me strange errors. 我想做的是编辑CSV文件,以显示新的数字
10
因为有20个苹果并且用户购买了10个。我尝试了各种方法,但是它们都给我带来奇怪的错误。 My expected output would be: 我的预期输出将是:
Item # Item name Item stock
12345670 Apple 20
What would you like to buy?: 12345670
How much would you like to buy?: 10
You have bought 10 apple(s) for a price of £7
There are 10 apples left in stock
If the user purchases too many apples: 如果用户购买太多苹果:
Item # Item name Item stock
12345670 Apple 20
What would you like to buy?: 12345670
How much would you like to buy?: 30
There are not enough apple(s) in stock to buy that amount
Would you like to buy all there is?: yes
You have bought 20 apple(s) for the price of £14
This is my code 这是我的代码
import csv
restart = 10
list1 = []
price = 0
print("Type 'end' to end")
while restart == 10:
file1 = open("CSV File TASK 2.csv", "rt")
file2 = csv.reader(file1)
print(" ")
order = input("Type the item number of your chosen number: ")
if order == 'end':
break
for row in file2:
for field in row:
if order in field:
amount = int(input("How much of that item?: "))
row3 = int(row[3])
if amount > row3:
print("There is not enough of that item in stock")
print("Please try again")
continue
row2 = float(row[2])
row1 = str(row[1])
price = amount * row2 + price
newstock = row3 - amount
print("You have bought {} {}(s) for the price of £{:.2f}".format(amount, row1, price))
print("Your subtotal is currently at {:.2f}".format(price))
receipt = ("{} {} {} {} {}".format(row[0]+" ", row[1], str(amount), "{:10.2f}".format(float(row[2])), "{:10.2f}".format(amount * float(row[2]))))
list1.append(receipt)
print('\n'.join('{}: {}'.format(*k) for k in enumerate(list1)))
Python 3.5.2. Python 3.5.2。 Please and thanks in advance.
请先谢谢。
You could use this: 您可以使用此:
import csv
f = open('test.csv', 'r') # Here your csv file
r = csv.reader(f)
lines = [l for l in r]
ItemX = 0
Item = input("What would you like to buy? ")
Amount = input("How much would you like to buy? ")
for x in range(len(lines)):
if lines[x][0] == Item:
ItemX = x
else:
continue1 = True # Does nothing
f.close()
fw = open('test.csv', 'w') # Here your csv file
lines[ItemX][2] = float(lines[ItemX][2]) - float(Amount)
writer = csv.writer(fw)
writer.writerows(lines)
fw.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.