Matthew Lund
Matthew Lund

Reputation: 4032

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

Upvotes: 4

Views: 11535

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602715

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

Upvotes: 11

Related Questions