biop91
biop91

Reputation: 61

Write output of nested for loop to .csv file

I have a nested for loop that produces a sequence of numbers that I need written to a .csv file, under the column name 'position' (each number in a new row). Below is the nested for-loop.

for i in range(140):
    for j in range(21):
        print(i+1)    

Any help is appreciated!

Upvotes: 1

Views: 145

Answers (1)

Parn
Parn

Reputation: 918

import csv

with open('output.csv', mode='w') as csv_file:
    fieldnames = ['position']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

    for i in range(140):
        for j in range(21):
            writer.writerow({'position': i + 1})

Upvotes: 1

Related Questions