Python os.path.commonprefix-是否存在面向路径的函数? [英] Python os.path.commonprefix - is there a path oriented function?
问题描述
所以我有这个python代码:
So I have this python code:
print os.path.commonprefix([r'C:\root\dir',r'C:\root\dir1'])
实际结果
C:\root\dir
所需结果
C:\root
问题1
基于os.path.commonprefix
文档:
返回最长路径前缀(按字符输入)
Question 1
Based on os.path.commonprefix
documentation:
Return the longest path prefix (taken character-by-character)
是否存在类似的功能:
返回最长路径前缀(由dir获取的dir )
Is there a similar function that:
Return the longest path prefix (taken dir by dir)
如果commonprefix
是在os.path
中实现的,为什么它不是面向路径的,这意味着返回我想要的结果而不是真实的结果?
if commonprefix
is implemented in os.path
why isn't it path oriented, meaning return my desired result and not the real one?
我可以自己轻松实现此功能,但是如果已经实现,为什么不使用它呢?
I can implement this easily by myself but if it is already implemented why not using it?
推荐答案
有面向路径的功能吗?
is there a path oriented function?
否,是的. commonprefix()
可以处理任意序列,而不仅仅是字符串.
no and yes. commonprefix()
can work with arbitrary sequences, not just strings.
将路径拆分为多个组件,然后在其上调用commonprefix()
:
Split the path into components and call commonprefix()
on that e.g.:
>>> import os
>>> from pathlib import PureWindowsPath
>>> a, b = map(PureWindowsPath, [r'C:\root\dir', r'C:\root\dir1'])
>>> PureWindowsPath(*os.path.commonprefix([a.parts, b.parts]))
PureWindowsPath('C:/root')
这篇关于Python os.path.commonprefix-是否存在面向路径的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!