In Python 2, is it possible to get the real path to a file object after changing directories?

In Python 2, is it possible to get the real path to a file object after 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 to the file on disk, and the second does not. Is there a way to get the path to the disk file after chdir ? Ideally, I would like to get a general answer that would work even if I didn't create the file myself.

I have no actual use for this, I'm just curious.

+4
source share
2 answers

sure that

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

while you use the absolute path when initializing it

as Martijn Pieters points out, you can also do

 f=file(os.path.abspath('fname'),"w") #or os.path.realpath , etc print f.name 
+1
source

... this works if I create the file object myself. But what if I weren't? What if I got it in a function? I would prefer a more general answer (and I edited the question to reflect that).

I don’t think that the full path will probably be saved anywhere inside Python, but you can request the OS for this 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.

+1
source

Source: https://habr.com/ru/post/1481994/


All Articles