如何将字典保存到 csv,其中每个键都有不同的行
How to save a dictionary to a csv where each key has a different row
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。
请 post 提供有效的代码,并提前致谢。
我认为您的错误可能在您的 "writer.writerow" 行中,并且可能与字典 keys/values 之间存在一些混淆。
每个 "writerow" 都应该在每一行中写一个一维列表。您在行中定义为 "row" 的内容:
for key, row in products.items():
其实就是字典key的value。是的,该值的数据类型恰好是一个列表(或一行),但该列表是字典 key 的 value指向。
您的代码并没有试图一次写入一个列表行。它实际上是在尝试将嵌套列表写入可视电子表格中的每一行。这是因为您的 Dictionary Key 的值本身就是一个 List 对象,它将一个列表放在另一个 writerow 列表中。
[ KeyName , ValueObject ]
因为我们的 ValueObject 是一个列表,所以我们在列表中有一个列表。
使用您的示例库存文件,这就是大多数 python 文件阅读器解释电子表格中每一行的样子:
[ KeyName , [ List, Of, Row, Values ] ]
这是具有 2 个维度的嵌套列表。一行中只能写入 2 个电子表格单元格。解决这个问题的方法是确保 "writer.writerow" 一次只写一个一维列表。
完成此操作的一种简单方法是将 2 个单独的列表连接成 1 个单独的行列表。
但是,由于您将值标记为 "row" 并将其中一个行项目标记为 "value",如果我们坚持您的上下文,我们应该能够连接该行值(这是一个列表 ) 和与之关联的键名。
for key, row in products.items():
writer.writerow ( [ key ] + row )
由于您的 "row" 值变量在这种情况下已经是一个列表,我们可以简单地将字典键读取为它自己的列表对象,以便在一个列表(和 1 行)中轻松连接。
那么 writerow 一次只写 1 个列表,该列表中的每个项目都放在 csv 文件中它自己的时间顺序单元格中。
根据您评论中的规范:
mydict = {'23456789': ('TV', '2000', '22', '0', '20'), '12345678': ('Fridge', '1000', '24', '0', '20'), '34567890': ('DVD', '10', '23', '0', '20')}
with open("out.csv", "w") as f:
for key in mydict:
f.write(key + "," + ",".join(mydict[key]))
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。 请 post 提供有效的代码,并提前致谢。
我认为您的错误可能在您的 "writer.writerow" 行中,并且可能与字典 keys/values 之间存在一些混淆。
每个 "writerow" 都应该在每一行中写一个一维列表。您在行中定义为 "row" 的内容:
for key, row in products.items():
其实就是字典key的value。是的,该值的数据类型恰好是一个列表(或一行),但该列表是字典 key 的 value指向。
您的代码并没有试图一次写入一个列表行。它实际上是在尝试将嵌套列表写入可视电子表格中的每一行。这是因为您的 Dictionary Key 的值本身就是一个 List 对象,它将一个列表放在另一个 writerow 列表中。
[ KeyName , ValueObject ]
因为我们的 ValueObject 是一个列表,所以我们在列表中有一个列表。
使用您的示例库存文件,这就是大多数 python 文件阅读器解释电子表格中每一行的样子:
[ KeyName , [ List, Of, Row, Values ] ]
这是具有 2 个维度的嵌套列表。一行中只能写入 2 个电子表格单元格。解决这个问题的方法是确保 "writer.writerow" 一次只写一个一维列表。
完成此操作的一种简单方法是将 2 个单独的列表连接成 1 个单独的行列表。
但是,由于您将值标记为 "row" 并将其中一个行项目标记为 "value",如果我们坚持您的上下文,我们应该能够连接该行值(这是一个列表 ) 和与之关联的键名。
for key, row in products.items():
writer.writerow ( [ key ] + row )
由于您的 "row" 值变量在这种情况下已经是一个列表,我们可以简单地将字典键读取为它自己的列表对象,以便在一个列表(和 1 行)中轻松连接。
那么 writerow 一次只写 1 个列表,该列表中的每个项目都放在 csv 文件中它自己的时间顺序单元格中。
根据您评论中的规范:
mydict = {'23456789': ('TV', '2000', '22', '0', '20'), '12345678': ('Fridge', '1000', '24', '0', '20'), '34567890': ('DVD', '10', '23', '0', '20')}
with open("out.csv", "w") as f:
for key in mydict:
f.write(key + "," + ",".join(mydict[key]))