比较python中的两条路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21158667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing two paths in python
提问by Jagannath Ks
Consider:
考虑:
path1 = "c:/fold1/fold2"
list_of_paths = ["c:\fold1\fold2","c:\temp\temp123"]
if path1 in list_of_paths:
print "found"
I would like the if statement to return True, but it evaluates to False,
since it is a string comparison.
我希望 if 语句返回True,但它的计算结果为False,因为它是一个字符串比较。
How to compare two paths irrespective of the forward or backward slashes they have? I'd prefer not to use the replacefunction to convert both strings to a common format.
如何比较两条路径而不考虑它们的正斜杠或反斜杠?我不希望使用该replace函数将两个字符串转换为通用格式。
采纳答案by falsetru
Use os.path.normpathto convert c:/fold1/fold2to c:\fold1\fold2:
使用os.path.normpath转换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
os.path.normpath(path1) in map(os.path.normpath, list_of_paths)also works, but it will build a list with entire path items even though there's match in the middle. (In Python 2.x)
os.path.normpath(path1) in map(os.path.normpath, list_of_paths)也可以,但即使中间有匹配项,它也会构建一个包含整个路径项的列表。(在 Python 2.x 中)
On Windows, you mustuse os.path.normcaseto compare paths because on Windows, paths are not case-sensitive.
在 Windows 上,您必须使用os.path.normcase来比较路径,因为在 Windows 上,路径不区分大小写。
回答by Aswin Murugesh
Store the list_of_paths as a list instead of a string:
将 list_of_paths 存储为列表而不是字符串:
list_of_paths = [["c:","fold1","fold2"],["c","temp","temp123"]]
Then split given path by '/' or '\' (whichever is present) and then use the inkeyword.
然后用“/”或“\”(以存在者为准)分割给定的路径,然后使用in关键字。
回答by user4815162342
Use os.path.normpathto canonicalize the paths before comparing them. For example:
用于os.path.normpath在比较路径之前规范化路径。例如:
if any(os.path.normpath(path1) == os.path.normpath(p)
for p in list_of_paths):
print "found"
回答by user2357112 supports Monica
回答by Jonathon Reinhart
All of these answers mention os.path.normpath, but none of them mention os.path.realpath:
所有这些答案都提到了os.path.normpath,但没有一个提到os.path.realpath:
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.
os.path.realpath(path)返回指定文件名的规范路径,消除路径中遇到的任何符号链接(如果操作系统支持它们)。
2.2 版中的新功能。
So then:
那么:
if os.path.realpath(path1) in (os.path.realpath(p) for p in list_of_paths):
# ...

