Reputation: 136
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?
Upvotes: 1
Views: 152
Reputation: 136
Thank you Random Davis!
I READ THE DOCUMENTATION and experimented some further and came up with this solution:
for hour in clocktimes:
if hour in hourtimes:
data = [hour, hourtimes[hour]]
writer.writerow(data)
else:
data = [hour, 0]
writer.writerow(data)
The data to be written is added to an array which is accepted by the writerow() method. Output is now as I wanted which is:
...
7,0
8,0
9,0
10,0
11,144
12,112
13,80
...
Upvotes: 1