Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Save Print output in csv file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading