How can the output of a python program be saved in a txt file?
How can the output of a python program be saved in a txt file?
Assuming that you are running on any Unix system, you have several ways to force the output in a file.
On the one hand, if you want all the output to be redirected to the file , you should use:
python code.py &> file.txt
In the case of wanting to limit only standard output to such a file you should redirect only STDOUT :
python code.py > file.txt
or, for error , STDERR :
python code.py 2> file.txt
As specific cases, if you want to save only the standard output , but not the error output, the code to use would be:
python code.py > file.txt 2> /dev/null
And finally, if you want to save in a file besides seeing, on screen , such a result, you can use tee :
python code.py | tee file.txt