4

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.

Junuxx
  • 14,011
  • 5
  • 41
  • 71
Trebor Rude
  • 1,904
  • 1
  • 21
  • 31

2 Answers2

1

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
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • 1
    or better still, use `os.path.abspath('fname')` – Martijn Pieters May 21 '13 at 16:35
  • Under the hood, `os.path.abspath('fname')` is effectively `os.path.join(os.getcwd(), 'fname')`, but with nicer handling of relative paths including `.` and `..` references. – Martijn Pieters May 21 '13 at 16:40
  • True, 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). – Trebor Rude May 21 '13 at 16:48
  • provide a helper function called createFile(fname) or something that ensures an absolute path on the file object returned ... – Joran Beasley May 21 '13 at 17:26
1

...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.

Aya
  • 39,884
  • 6
  • 55
  • 55
  • you could use `/proc/self/`. See [Getting Filename from file descriptor in C](http://stackoverflow.com/q/1188757/4279) (there are also answers for Windows and OSX). – jfs May 21 '13 at 18:22