Save Print output in csv file

Solution 1:

To write a row to a CSV file, the writerow() function argument should be an iterable object (e.g. list).

The following code will create a CSV file with one column of numbers ranging from 2000 to 2999.

import csv

with open('op2.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['a'])  # output header row as first line
    for x in range(2000, 3000):
        writer.writerow([f'hi{x}'])        

If want to format variables using the print() function then you can use str.format() method or formatted string literals (also called f-strings for short). Code above uses f-string f'hi{x}' to format each value of x to a string of the form: hi2000, hi2001, etc.