Python Forum

Full Version: file detection
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
you can detect if x is a float like:

if isinstance(x,float):
    ...
so how do you detect if x is a file?
isinstance(x, file)
file is no longer a built-in functions for Python 3.x.
This work Python 2.7 and 3.6.
>>> from io import IOBase

>>> f = open('hello.txt')
>>> isinstance(f, IOBase)
True
But remember type checking is really not good at all in Pythons,so use it sparse.
Quote:EAFP(Easier to ask for forgiveness than permission).
So let error occur then can catch it with try except.

LBYL(Look before you leap) check type before error occur,like in language like C/C++.
if you have the path you can check with os.path.isfile
i want to check if what is passed to a function in stdout= is a file or file descriptor.  for file descriptor, checking for int is good enough.  but assuming whatever is not int is a file i think is not good enough ... something might succeed with something else.  i want an explicit test.  right now i am checking if 'fileno' in stdout.  i want this to work in the widest range of python versions as possible but at least 2.6-2.7 and 3.3-.
(Feb-11-2017, 02:42 AM)Skaperen Wrote: [ -> ]but assuming whatever is not int is a file i think is not good enough ... something might succeed with something else.
Why is that not good enough? If it quacks like a duck, treat it like a duck. If it doesn't quack, then just raise an exception.

I also don't understand what you mean about file descriptors. That sounds like C-talk. In Python, it's an object, not a numeric.
(Feb-11-2017, 03:54 AM)micseydel Wrote: [ -> ]I also don't understand what you mean about file descriptors. That sounds like C-talk. In Python, it's an object, not a numeric.

as in os.pipe()  ... how i connect 2 or more processes together in a command pipeline.
Just ask nicely if it's a file?

>>> import os
>>> os.path.isfile("test.db")
True
>>> os.path.isfile("pipe://4433828") #...or whatever
False
File vs file descriptor is needed in C, when you have to deal with file handles.
I have never cared in python, and it hasn't hurt me yet.
If you want strict type checking then you should go back to programming in C.
In [1]: import os.path

In [2]: with open('39768.txt', 'r') as f:
   ...:     print(os.path.isfile(f.fileno()))
   ...:     
True