简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM