Python - 有没有一种方法可以将相对路径转换为绝对路径?

4
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))

输出:

/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

这些文件路径能正常工作,但我希望看到它们是绝对路径(不含任何../ - 我不知道为什么在意这个,可能是强迫症。我想在日志记录时也能更容易地看到绝对路径。标准的Python库(我使用的是3.2)中是否有内置方法可以将这些转换为绝对路径?如果没有也没关系,只是搜索了一下只找到了第三方解决方案。

编辑:看起来我想要的是os.path.abspath(file)。因此,修改后的源代码将如下所示(请注意,我没有测试过,只是随口说说):

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))

输出:

/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


可能是如何在Python中获取绝对文件路径的重复问题。 - Tobias Kienzler
1个回答

11
请注意,您的路径已经是绝对路径 -- 它们以 / 开头。但它们尚未归一化,可以使用os.path.normpath()进行归一化处理。

2
谢谢。我可能没有表达清楚我的问题,但是阅读关于normpath()的内容让我看到了实际上我真正需要的abspath()。再次感谢。 - Matthew Lund

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接