0

I'm currently puzzling around this piece of code.

What exactly does

open(0)

do?

I already looked up the docs or tried to find something in the internet but no clues.

The codesnippet where this code is used:

map(abs,map(int,open(0).read().split()))

Thanks ^

Ari24
  • 370
  • 5
  • 12
  • 2
    Does this answer your question? [Integer File Descriptor "0" in open()](https://stackoverflow.com/questions/53898231/integer-file-descriptor-0-in-open) – Sandeep Gusain Mar 19 '21 at 20:14

1 Answers1

6

0 is the file descriptor associated with stdin (1 corresponds to stdout, 2 to stderr). open takes int file descriptors as an argument, not just paths, so passing 0 is legal. This is just a somewhat obscure way to create a file object bound to stdin without needing to import sys.

The flaw with it is that, when it is closed, it will close the file descriptor 0 (since closefd=False was not passed), so sys.stdin will be closed without realizing it (though it'll probably figure it out when if someone tries to use it).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271