【发布时间】:2016-03-22 15:18:46
【问题描述】:
import time
import csv
def file_reader():
product_location = {}
location = 0
with open('stockfile.csv', mode='r+') as f:
reader = csv.reader(f)
#next(reader) Can be included if I have headers to skip it
products = {rows[0]: (rows[1],rows[2],rows[3],rows[4],rows[5]) for rows in reader}
global products
with open('stockfile.csv', mode='r+') as f:
for line in f:
lines = line
print(lines)
product_location[line.split(',')[0]] = location
global product_location
f.close()
total=0
with open('stockfile.csv','r+') as f:
for line in f:
product_location[line.split(',')[0]] = location
location += len(line)
total = 0
while True:
file_reader()
GTIN = input("\nPlease input GTIN or press [ENTER] to quit:\n")
if GTIN == "":
break
if(GTIN not in products):
print("Sorry your code was invalid, try again:")
continue
row = products[GTIN]
description = row[0]
value = row[1]
stock = row[2]
additional_stock = row[3]
target_stock = row[4]
print("Updating stock levels back to target level")
stock = int(stock) + int(additional_stock)
print('GTIN: ', GTIN)
print('You have selected: ', description)
print('The price of this product is: ', value)
print('Stock: ', stock)
quantity = input("Please input the quantity required: ")
new_stock = int(stock) - int(quantity)
if int(quantity) > int(stock):
print("Sorry we don't have enough in stock please order again")
print("Please try a different product or a smaller quantity: ")
continue
else:
new_stock = int(stock) - int(quantity)
if int(new_stock) < int(target_stock):
answer = input("The stock is below target, if you would like to top up the product to the target stock level press [ENTER]")
if answer == "":
required = int(target_stock) - int(new_stock)
added_stock = input("This is the target stock: %s, you must enter a minimum of %s" % (target_stock,required))
stock= int(new_stock)+int(added_stock)
while int(stock) < int(target_stock):
print("Sorry input more please:")
continue
if int(stock) > int(target_stock):
additional_stock = 0
products[GTIN] = row[0],row[1],str(stock),str(additional_stock),row[4]
print(products[GTIN])
print(products)
writer = csv.writer(open('stockfile.csv','w',newline=''))
for key, row in products.items():
writer.writerow([key, value])
else:
additional_stock = int(target_stock) - int(new_stock)
#I need to do the same here and change the dictionary and then send it to the CSV
product_total = (int(quantity) * int(value))
total = total + product_total
print('Total of the order is £%s' % total)
我无法弄清楚如何使用这种格式将字典发送回 csv(这是它在开始时被调用时的格式,我想以同样的方式发送回信息)。这就是库存文件的样子:This is the format I want the dictionary to be sent back in as well as when it is opened。 请同时发布有效的代码并提前感谢。
【问题讨论】:
-
请提供MVCE:显示字典现在的样例,以及所需的输出csv(文本)。
-
@L3viathan 运行代码时会显示字典的示例,所需的输出是代码下注释中蓝色文本的格式(单击蓝色文字查看库存文件图片) .谢谢
-
-
@L3viathan 我明天真的需要这个代码,如果你能给我一种解决方案,我将非常感激,因为我真的需要帮助。如果您的代码正常运行,我非常感谢您。
-
然后给我看(简略版)字典。我不想运行您的脚本,而且无论如何我都缺少要求。 StackOverflow 不是代码编写服务。
标签: python csv python-3.x dictionary export-to-csv