Python output txt

How can I export all the outputs I get in python as a txt file?
I don’t want to apply to each result one by one anyway, not every result is a string.

As in all your print() outputs? There’s a couple ways I would go about this. You could open a file as an output at the beginning of your program and then instead of using print, write to it every time, just make sure to close it at the end.
For the sake of simplicity, I’d probably write a function to act as my new “print”. Open a file, convert it’s args to strings, write them, and close the file. It be a little more overhead to open and close the file every time, but it keeps things cleaner. It’s a case of how efficient you need things to be.

I encourage you to try this on your own but here’s an idea.

spoiler warning
def output(args):
  fp = open("output.txt", "a")
  for arg in args:
    fp.write(str(arg) + '\n')


Note the use of append mode. If we write every time you won’t be able to keep your previous output.
This isn’t perfect of course. There’s a few minor… not quite flaws, but inefficiencies here. Variable args might make things easier instead of requiring an indexable variable.
How about speed? Writing once for every argument will be rather slow. Constructing a buffer might be a bit faster.

Here’s another idea, but once again I encourage you to try on your own first:

double spoiler
def output(*args):
  with open("output.txt", "a") as fp:
    fp.write('\n'.join([str(i) for i in args]) + '\n')

I haven’t tested much, so probably some more flaws here. I’m not too keen of the double for loop (one for the list comp, and one in the .join().

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.