1

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?

4
  • 1
    What is the hourtimes variable? Commented Apr 5, 2017 at 17:13
  • 1
    You are passing a single string to writerow. The row in writerow(row) is supposed to be a sequence of strings or numbers, according to the documentation. Your line writer.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 use writerow, or pass it the correct data. Commented Apr 5, 2017 at 17:17
  • Let us know of the hourtimes variable Commented Apr 5, 2017 at 17:53
  • I clearly state that the hourtimes variable is a dictionary consisting of integers as keys and values. Commented Apr 5, 2017 at 18:02

1 Answer 1

1

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
...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.