I need to convert json to csv for an inventory feed with no headers and I have no problem with the conversion but the column order is getting changed. Is there a way to maintain the column order? Here is what I have:
acmeInventory = Stock.objects.filter(product__type__in=(1, 9), status=1,
product__acmesells=True)
data=[]
for item in acmeInventory:
sku = item.product.sku
if sku == 'PROVTi-BK':
sku = 'VTi-BK'
if sku == 'PROVT-BK':
sku = 'VT-BK'
quantity = int(item.stock)
if quantity < 50:
quantity = 0
itemDict={
'Manufacturers Item #':sku,
'Quantity Available': str(quantity),
'Stocking Unit of Measure': 'EA',
'Date Available': str(today),
'Item Description': item.product.name,
}
data.append(itemDict)
print(data)
keys = data[0].keys()
with open('AcmeIAV220.csv','w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file,keys)
dict_writer.writerows(data)
ftp = ftplib.FTP(host,user,password)
ftp.encoding = "utf-8"
with open('AcmeIAV220.csv', "rb") as file:
ftp.storbinary("STOR AcmeIAV220.csv", file)
ftp.dir()
CodePudding user response:
Try using an OrderedDict instead of dict
Here is an example: OrderedDict in Python (GeeksforGeeks)