I am trying to write data in csv format to a file. The data I am writing is pairs of integers. The inconsistency is that when the number 10 is written, I get a comma between the "1" and the "0". This just happens for the number 10, not for 11 etc.
Code:
clocktimes = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
with open('testfile.csv', 'w') as tf:
writer = csv.writer(tf)
for hour in clocktimes:
if hour in hourtimes:
writer.writerow( str((hour)).split(',') + str((hourtimes[hour])).split(',') )
else:
writer.writerow( (str(hour)) + (str(0)) )
(hourtimes is a dictionary consisting of integers as keys and values)
Output file:
7,0
8,0
9,0
1,0,0
11,144
12,112
13,80
Does anyone know why this is happening and what I can do to prevent this outcome?
hourtimesvariable?rowinwriterow(row)is supposed to be a sequence of strings or numbers, according to the documentation. Your linewriter.writerow( (str(hour)) + (str(0)) )is treating the string as a list of characters, and writing them one by one to your CSV. Either don't usewriterow, or pass it the correct data.