0

Is it possible to print to screen and save to file in one-line?

The following saves to file:

with open('file.txt', 'a') as f:
   print('hello world', file=f)

And currently to print to screen and save to file would have to do the following:

print['hello world')
print('hello world', file=f)

I can't find any answers out there for one-line.

I guess a function can be defined to avoid lines in code, but still wondering if it is possible to do all in one line

martineau
  • 119,623
  • 25
  • 170
  • 301
shabuboy
  • 41
  • 6
  • 1
    Does this answer your question? [Printing to screen and writing to a file at the same time](https://stackoverflow.com/questions/9321741/printing-to-screen-and-writing-to-a-file-at-the-same-time) – azro May 28 '20 at 20:33
  • Write a method that do both, then use this method in one-line, `printBoth("This is content")` – azro May 28 '20 at 20:33
  • Logging is not quite what I was looking for @azro, but I will revisit it in case I cannot find a solution. But yes, a method to do both sounds doable – shabuboy May 29 '20 at 17:09

2 Answers2

1

You are looking for a tee fitting for Python. Such a package - tee - exists in PyPI.

You can also build one yourself with a few lines of code - the original author of a big package I maintain did just that, and my code uses it to this day. Of source, there is not need for that, since the package is available.

Amitai Irron
  • 1,973
  • 1
  • 12
  • 14
  • Thanks @Amitai Irron! This seems doable, even though I was trying to avoid unnecessary code lines to make it cleaner, but it seems there no way to avoid that. – shabuboy May 29 '20 at 17:20
-2

Try the snipette below, I had success with it in Jupyter Notebook

f=open('file.txt','a');print('hello world');f.write('hello world');f.close()
Steven M
  • 204
  • 1
  • 4
  • 13