Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Any way to turn relative paths into absolute paths?

current_working_directory = os.getcwd()
relative_directory_of_interest = os.path.join(current_working_directory,"../code/framework/zwave/metadata/")

files = [f for f in os.listdir(relative_directory_of_interest) if os.path.isfile(os.path.join(relative_directory_of_interest,f))]

for f in files:
    print(os.path.join(relative_directory_of_interest,f))

Output:

/Users/2Gig/Development/feature_dev/scripts/../code/framework/zwave/metadata/bar.xml
/Users/2Gig/Development/feature_dev/scripts/../code/framework/zwave/metadata/baz.xml
/Users/2Gig/Development/feature_dev/scripts/../code/framework/zwave/metadata/foo.xml

These file paths work fine but part of me would like to see these be absolute paths (without any ../ - I don't know why I care, maybe I'm OCD. I guess I also find it easier in logging to see absolute paths. Is there something built into the standard python libraries (I'm on 3.2) that could turn these into absolute paths? No big deal if not, but a little googling only turned up third-part solutions.

EDIT: Looks like what I want what os.path.abspath(file)) So the modified source could above would now look like (not that I didn't test this, it's just off the cuff):

current_working_directory = os.getcwd()
relative_directory_of_interest = os.path.join(current_working_directory,"../code/framework/zwave/metadata/")

files = [f for f in os.listdir(relative_directory_of_interest) if os.path.isfile(os.path.join(relative_directory_of_interest,f))]

for f in files:
    print(os.path.abspath(f))

Output:

/Users/2Gig/Development/feature_dev/scripts/ZWave_custom_cmd_classes (08262010).xml /Users/2Gig/Development/feature_dev/scripts/ZWave_custom_cmd_classes (09262010).xml /Users/2Gig/Development/feature_dev/scripts/ZWave_custom_cmd_classes (09262011).xml

like image 999
Matthew Lund Avatar asked Dec 22 '22 02:12

Matthew Lund


1 Answers

Note that your paths are already absolute -- they start with /. They are not normalized, though, which can be done with os.path.normpath().

like image 151
Sven Marnach Avatar answered Dec 26 '22 14:12

Sven Marnach