0

I want to save this print output to CSV file but this code is not working, how can I save this output to CSV?

import csv

for x in range(2000, 3000):
    print('hi', x, sep='')

f = open('op2.csv', 'w')
writer = csv.writer(f)
writer.writerow(print())
f.close()

I want to save on CSV like this

hi2000
hi2001
hi2002
Rasedul Islam
  • 77
  • 1
  • 9
  • Please take a moment to read [ask] and edit your question to include more details, including what you want the contents of the CSV to be. – Code-Apprentice Jan 11 '22 at 16:21
  • The big change that needs to be made here is moving your `writer.writerow` to be inside of your `for` loop. Just like `print` executes once for that `range(2000,3000)` you also need to `writerow` once per iteration in that range. – JNevill Jan 11 '22 at 16:32
  • If you only want one column, why use a CSV file? – Tim Pietzcker Jan 11 '22 at 16:51
  • @TimPietzcker I want one column with hi2000 and I will create more than 5 columns like hi3000, hi4000, etc in different rows, that's why I'm using a CSV file. – Rasedul Islam Jan 11 '22 at 17:26
  • Does this answer your question? [How to save the output of the print statements to a new file?](https://stackoverflow.com/questions/38832545/how-to-save-the-output-of-the-print-statements-to-a-new-file) – Gino Mempin May 21 '22 at 10:10

1 Answers1

2

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.

CodeMonkey
  • 22,825
  • 4
  • 35
  • 75