How to create a new file based on python code via terminal?

I am a new user of Linux. I have written a Python program with a loop that runs 10 times and prints one line each time. I saved it as printing.py Now I want to use the terminal to ensure that the printout is saved in a new file.

The code I use is:

counter = 1
while counter <= 10:
print("This is line", counter)
counter = counter +1

However, I don't know how to get from the program that I saved as printing.py via terminal to a new file "result".


Solution 1:

You can redirect the output of your program by using the > operator. The output is then written to the given file instead of the terminal:

python3 printing.py > result

Note that the text is not appended, but replaces the current content of the file. If you want to append the output to the file, use the >> operator.

There is also a way to get the output on the terminal and in the file, so you can see what's happening. Just pipe the output to the command tee and it will print it to your terminal and to the file. You can imagine this command as a T-shaped pipe which redirects its input to two outputs.

python3 printing.py | tee result

Again this will overwrite the current content of your file.