比较python中的两条路径

2024-09-25 02:36:29 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑:

path1 = "c:/fold1/fold2"
list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]

if path1 in list_of_paths:
    print "found"

我希望if语句返回True,但它的计算结果是False, 因为这是一个字符串比较。

如何比较两条路径,而不考虑它们的正斜杠或反斜杠?我不希望使用replace函数将两个字符串转换为通用格式。


Tags: of字符串inif语句templistpaths
3条回答

使用^{}c:/fold1/fold2转换为c:\fold1\fold2

>>> path1 = "c:/fold1/fold2"
>>> list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]
>>> os.path.normpath(path1)
'c:\\fold1\\fold2'
>>> os.path.normpath(path1) in list_of_paths
True
>>> os.path.normpath(path1) in (os.path.normpath(p) for p in list_of_paths)
True
    {

在Windows上,必须使用^{}比较路径,因为在Windows上,路径不区分大小写。

^{}模块包含几个函数来规范化文件路径,以便等效路径规范化为同一字符串。您可能需要normpathnormcaseabspathsamefile或其他工具。

所有这些答案都提到os.path.normpath,但没有一个提到^{}

os.path.realpath(path)

Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).

New in version 2.2.

那么:

if os.path.realpath(path1) in (os.path.realpath(p) for p in list_of_paths):
    # ...

相关问题 更多 >