python os.path.isfile() returns True for some integers

Viewed 563

Surely I am missing something obvious. How can os.path.isfile() return True when given a scalar value?

>>> for i in range(0,20):    print(os.path.isfile(i))
... 
False
False
False
False
False
False
False
False
False
False
False
False
False
True
True
True
True
True
True
True

I am executing this from an empty directory. Python 3.6. I've looked at other questions about os.path.isfile() but I did not find an answer to this.

1 Answers

It's all in the docs:

  • os.path.isfile returns True if path is an "existing" regular file.
  • path "exists" if os.path.exists returns True
  • since version 3.3 path can be an integer - if it is an open file descriptor os.path.exists returns True
  • file descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. (The name "file descriptor" is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.)
Related