Score:0

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

ae flag

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

ru flag
Well, firstly, your code is invalid as copy/pasted into your post. You'll immediately get an indentation error because items under the while loop need to be indented. Secondly, have you considered simply opening the file in Python and written the result to the file, clobbering whatever is in there first?
Score:2
pr flag

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.

Score:0
cn flag

Copy and paste the following into a file test.py

#!/usr/bin/env python3
#
counter = 1
while counter <= 10:
   print("This is line", counter)
   counter = counter + 1

Now run the commands

chmod +x test.py
./test.py > output.txt

Output should be

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
ru flag
This outputs to command line, but I think they want it in a file.
Thomas Aichinger avatar
cn flag
Yes you are right, I forgot to redirect it. Just fixed that.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.