0

Here's my situation: after running a Python file in VS Code I get a bunch of results in the terminal (in my case, several integers). Now, I want to export what is displayed on the terminal to a txt. file.

I have tried this:

import sys
f = open("out.text", 'w')
sys.stdout = f
print ("out.text", file=f)
f.close()

Basically, I am looking for something like this:

with open('out.txt', 'w') as f:
    print('The data I see in the terminal window', file=f)

Now, how do i get this object: 'The data I see in the terminal window'?

P.S. I am very new to programming.

  • `with open("file1.txt", "r") as f_in: with open ("file2.txt", "a") as f_out: lines = f_in.readlines() for l in lines: l=[l] print(l, file=f_out)` also seems to work if you really, really, really want to use the `print` function. P.S. I am utterly unable to properly format this code, hope you guys get it. – Catcher InTheRye Feb 09 '22 at 11:00

1 Answers1

0

You can use the write method to write to a file:

with open("out.text", "w") as f:
  f.write("out.text\n")
  f.write("Something else\n")

You need the \n to end the line and print the "Something else" to the next line.

You can use

with open("out.text", "a") as f:

to append the following write statements to the contents of the file.

To do both, i.e., print to the terminal and write to a file, you would need two commands, one for each:

with open("out.text", "w") as f:
  print("out.text")
  f.write("out.text\n")

  print("Something else")
  f.write("Something else\n")

Alternatively, you could redirect the terminal output when calling your script

python script.py > out.text

But this will not print anything on the terminal anymore either, but redirect everything to the file.

There is at least one other question on here that deals with this. Have a look here: How to redirect 'print' output to a file? And additionally search a bit more. There are several solutions to your problem, but having it both ways is gonna be tricky.

thortiede
  • 116
  • 3
  • Thanks for the reply, thortiede. But what I need to append/write to my out.text is what I see on the terminal AFTER I execute the command print. Basically, it's what's written on the terminal screen. – Catcher InTheRye Feb 04 '22 at 22:36
  • This also does not print to the terminal anymore, but reroutes your print statements to the file. Unless VS Code still prints it to the terminal. I do not see any benefit compared to simply using `write` statements in place of the `print` statements. – thortiede Feb 07 '22 at 10:54
  • Right. Using the 'write' method is way better than printing in this case. – Catcher InTheRye Feb 08 '22 at 10:23