[Tutor] Appending to CSV file puts data in wrong columns

Alan Gauld alan.gauld at btinternet.com
Thu Aug 29 19:50:23 EDT 2019


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



More information about the Tutor mailing list