to get name of file opened

Dave Angel davea at
Sat Mar 28 15:51:38 CET 2009

First question is why you need, and not the open() function.  
I'll guess that you need some of the access modes (e.g. for file 
sharing) that you get from the low level functions.  So assuming that:

I don't believe there's any way to use a fd ("file descriptor") to 
retrieve the file name that was perhaps passed to open.  There are ways 
to spelunk inside Windows, but they're not advisable. And I don't know 
what Unix might offer there.

So by the time fdopen() is invoked, the name is already gone.

Here's what I'd do.  Create your own open function that has the 
parameters of, but that will return an object derived from the 
file object.  Your derived object can have its own filename, but close() 
will know what to do.

Alternatively, you could encapsulate the line you showed, and just zap 
the name attribute of the existing file object.right when it's being 
returned by fdopen()

Visco Shaun wrote:
> Hi
> Is there any way to get the name of the file opened from the file object
> 'f' which i get through the code 
> f = os.fdopen("trial', os.O_WRONLY|os.O_CREAT), "w")
> The situation will be like i can access only the above variable 'f'.
> is having '<fdopen>' instead of filename 'trial'
> Or if not possible can anyone suggest a solution where my requirements
> are
> a) i need file access through os module
> b) i need file object and not file descriptor as its more easy to use

More information about the Python-list mailing list