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
5
  • Please take a moment to read How to Ask and edit your question to include more details, including what you want the contents of the CSV to be. Commented Jan 11, 2022 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. Commented Jan 11, 2022 at 16:32
  • If you only want one column, why use a CSV file? Commented Jan 11, 2022 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. Commented Jan 11, 2022 at 17:26
  • Does this answer your question? How to save the output of the print statements to a new file? Commented May 21, 2022 at 10:10

1 Answer 1

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.

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

2 Comments

It works but I need to save it with 1 columns, sep='' can't add to writer.writerow(['hi',x])
@RasedulIslam - use writer.writerow([f'hi{x}']) to output hi2000, etc.

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.