[Tutor] Appending to CSV file puts data in wrong columns
Cal97g .
cal.97g at gmail.com
Thu Aug 29 21:27:51 EDT 2019
As Alan has touched on here, Benjamin, the issue is the dictionary order.
In Python 2.7 dictionaries were intentionally randomly ordered and this
behaviour would result in this issue.
At some point in Python 3 dictionaries were changed to maintain order based
on insertion order.
In Python 3.3 they were changed again so that each session of Python would
produce a potentially different order.
The issue is you are passing *row.keys() *csv.DictWriter. This will not
maintain order.
You need to store your column values in an ordered datatype like a list.
def save_sku_and_price_data_to_csv(sku, price, path):
columns = ["sku", "price"]
row = {"sku": sku, "price": price}
with open(path, "a") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=columns)
writer.writerow(row)
print("adding", row, "to", path)
Callam
On Fri, Aug 30, 2019 at 12:51 AM Alan Gauld via Tutor <tutor at python.org>
wrote:
> On 29/08/2019 21:00, Benjamin Fishbein wrote:
> > Here’s the code, using the csv module. It adds a new row to an existing
> file.
> >
> > def save_sku_and_price_data_to_csv(sku, price, path):
> > row = {"sku": sku, "price": price}
> > with open(path, "a") as csvfile:
> > writer = csv.DictWriter(csvfile, fieldnames=row.keys())
> > writer.writerow(row)
> > print("adding", row, "to", path)
> >
> > Here’s the problem: It worked properly the first time I ran it, but
> today it has been writing the “sku”s in the “price” column and the “price”s
> in the “sku” column.
> > Any idea why this is or how to fix it?
> You don't say which version of python (or OS) you are using but there
> have been changes
> in the way dictionaries work that might make it significant. I don't
> think so but its worth
> stating just in case.
>
> Otherwise the function looks OK to me. Can we see the calling code too?
>
> --
>
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list