This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to os.chdir()
, so cannot use
f = file('test')
os.path.abspath(f.name)
Instead, I was wondering whether the following is a good solution - basically extending the file class so that on opening, the absolute path of the file is saved:
class File(file):
def __init__(self, filename, *args, **kwargs):
self.abspath = os.path.abspath(filename)
file.__init__(self, filename, *args, **kwargs)
Then one can do
f = File('test','rb')
os.chdir('some_directory')
f.abspath # absolute path can be accessed like this
Are there any risks with doing this?