Trebor Rude
Trebor Rude

Reputation: 1954

In Python 2, can I get the real path of a file object after changing directories?

In Python 2, is it possible to get the real path of a file object after an os.chdir()? Consider:

$ python
>>> f = file('abc', 'w')
>>> f.name
'abc'
>>> from os import path
>>> path.realpath(f.name)
'/home/username/src/python/abc'
>>> os.chdir('..')
>>> path.realpath(f.name)
'/home/username/src/abc'

The first call to realpath returns the path of the file on disk, but the second one does not. Is there any way to get the path of the disk file after the chdir? Ideally, I'd like a general answer, one that would work even if I didn't create the file object myself.

I don't have any actual use case for this, I'm just curious.

Upvotes: 4

Views: 1409

Answers (2)

Aya
Aya

Reputation: 42060

...that works if I create the file object myself. But what if I didn't? What if I received it in a function? I'd prefer a more general answer (and I've edited the question to reflect that).

I don't think the full path is likely to be stored anywhere in the Python internals, but you can ask the OS for the path, based on the file descriptor.

This should work for Linux...

>>> import os
>>> os.chdir('/tmp')
>>> f = open('foo', 'w')
>>> os.chdir('/')
>>> os.readlink('/proc/%d/fd/%d' % (os.getpid(), f.fileno()))
'/tmp/foo'

Not sure about Windows.

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114048

sure

f=file(os.path.join(os.getcwd(),"fname"),"w")

print f.name

as long as you use an absolute path when you initialize it

as Martijn Pieters points out you could also do

f=file(os.path.abspath('fname'),"w")  #or os.path.realpath , etc

print f.name

Upvotes: 0

Related Questions