Python Forum

Full Version: Want to Save Print output in csv file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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()
print() is a function. When you call the print() function it returns the value None. writerow(print()) will write None in the CSV file. If you want to print() a string and write the same string to a file you need to create the string, assign it to a variable, print the variable and write the variable to the file.
(Jan-11-2022, 03:09 PM)deanhystad Wrote: [ -> ]print() is a function. When you call the print() function it returns the value None. writerow(print()) will write None in the CSV file. If you want to print() a string and write the same string to a file you need to create the string, assign it to a variable, print the variable and write the variable to the file.

Can you write the code please, I am new in python and learning.
for a simple csv you don't need csv module, csv is also just a text file

with open('op2.csv', 'w') as f:
    for x in range(2000, 3000):
        row = f'hi{x}\n'
        f.write(row) # write line to file
(Jan-11-2022, 04:29 PM)Axel_Erfurt Wrote: [ -> ]for a simple csv you don't need csv module, csv is also just a text file

with open('op2.csv', 'w') as f:
    for x in range(2000, 3000):
        row = f'hi{x}\n'
        f.write(row) # write line to file

It works, Thank you so much!
(Jan-11-2022, 04:03 PM)Rasedul Wrote: [ -> ]Can you write the code please, I am new in python and learning.
You should give a try when a get suggestion doesn't matter it it's a bad way or not work,just to show some effort Wink
It's not need here to use csv module as pointed out,to show examples how it can be using csv module.

The same output as print().
import csv

with open('op2.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    var = 'hi'
    for x in range(2, 5):
        writer.writerow([f'{var}{x}'])
Output:
hi2 hi3 hi4
A comma between variable and loop result.
import csv

with open('op2.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    header = ['Word', 'Result']   
    var = 'hi'
    writer.writerow(header)
    for x in range(2, 5):
        writer.writerow([var, x])
Output:
Word,Result hi,2 hi,3 hi,4