Search code examples
python-3.xcsvfilerow

Python file write in csv, problem with row write


I am trying to write a csv with a set of 4 values (4 columns) for a infinite loop. I create a test code to try this, but when i run the code, the values i get in the csv are wrong.

import csv 

fields = ['Number1', 'Number2', 'Number3', 'Number4'] 

filename = "test.csv"

with open(filename, 'w') as csvfile: 
  csvwriter = csv.writer(csvfile) 
  csvwriter.writerow(fields) 
  for i in range(10):
    rows=[]
    for o in range(4):
      rows.append(str(o))
    csvwriter.writerows(rows)

And the values i get in the csv are:

Number1,Number2,Number3,Number4
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3

What is wrong with my code, or what i should modify to solve this problem?


Solution

  • You are calling writerows and not writerow inside the loop. That tells python to write the iterable as mulitple lines.