I'm using python 3.6.0. I have written dictionaries to CSV files before, but never on lines that already contains text. I am having trouble with that now. Here's my code:
import csv
f='/Users/[my name]/Documents/Webscraper/tests/output_sheet_1.csv'
bigdict = {'ex_1': 1, 'ex_2': 2, 'ex_3': 3}
with open(f, 'r+') as file:
fieldnames=['ex_1','ex_2','ex_3']
writer = csv.DictWriter(file, fieldnames=fieldnames,delimiter=',')
if '\n' not in file.readline()[-1]:
file.write('\n')
writer.writerow(bigdict)
When I run this, python appends the dictionary on the first line after the row containing the fieldnames, starting at the last cell that's below a fieldname. In other words, the first row contains many entries, including ex_1
, ex_2
, and ex_3
in the last three cells. In the second row, I have values stored in all cells except for those under ex_1
, ex_2
, and ex_3
, which are blank. Python writes the integer 1
below ex_3
, and writes 2
and 3
in the cells right of it.
I would like to re-position them so each number is under their respective fieldname cells. How do I do this, and why is this happening? Thanks.