The code `open(0)  # ?!` in a good-looking thumbnail.

Opening a file

In Python, we typically use the function open to open a file and read from it. In particular, the construct

with open(filepath, mode) as f:
    ...

is very common in Python.

Well, today I learned that the function open can accept the integer 0 to read from standard input.

That's because the function open accepts file descriptors as its argument, and 0 is the file descriptor for standard input.

1 is the file descriptor for standard output, and 2 is the file descriptor for standard error, so you can also write to these two streams by using the built-in open:

>>> stdout.write("Hello, world!\n")
Hello, world!
14
>>> stdout.close()

Knowing that you can read from stdin with open(0), you can type in multiline input in the REPL with ease:

>>> msg = open(0).read()
Hello,
world!
^Z
>>> msg
'Hello,\nworld!\n'

To stop reading, you need to go to an empty new line and press some magic key(s). (On Windows, it's Ctrl+Z. On Linux/Mac OS it may be Ctrl+D, not sure.)

That's it for now! Stay tuned and I'll see you around!

Improve your Python 🐍 fluency and algorithm knowledge 🎯

Get ready for 12 intense days of problem-solving. The β€œAlgorithm Mastery Bootcamp” starts December 1st and it will feature 24 programming challenges, live analysis sessions, a supportive community of like-minded problem-solvers, and more! Join now and become the Python expert others can rely on.

Previous Post Next Post

Blog Comments powered by Disqus.