tags:

views:

3692

answers:

3

Given a path such as

"mydir/myfile.txt"

How do I find the absolute filename relative to the current working directory in Python? E.g. on Windows, I might end up with:

"C:/example/cwd/mydir/myfile.txt"
+22  A: 
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
sherbang
+7  A: 
>>> import os
>>> os.path.abspath('mydir/myfile.txt')
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
Will Harris
+6  A: 

Better still, install the path.py module, it wraps all the os.path functions and other related functions into methods on an object that can be used wherever strings are used:

>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
Tom
Too bad they never got a proper filename abstraction module into the stdlib.
Torsten Marek