rasedul
(Rasedul Islam)
1
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(10, 55):
print('hi', x, sep='')
f = open('op2.csv', 'w')
writer = csv.writer(f)
writer.writerow(print())
f.close()
EpicWink
(Laurie O)
2
print
is a function which always returns None
, instead it writes to stdout (by default) as a side-effect.
In bash and zsh (on Linux and Mac OS), you can redirect (aka save) all of a command’s stdout (aka output) to a file like this:
python my-script.py > op2.csv
To change your current script to work without redirection, replace
writer.writerow(print())
with
for x in range(10, 55):
writer.writerow(["hi", str(x)])
1 Like
You should open the file, then write into it (and yes, you can use print
to do so). It is advisable to use context manager, so this code:
with open('print_to_file.csv', 'w') as f:
for i in range(1, 6):
print(i, file=f)
… result is print_to_file.csv file with following content:
1
2
3
4
5
1 Like