Python 检查目录是否为(文件系统)根目录
我有一个脚本,它搜索包含特定文件的目录,从当前目录开始,沿着树向上搜索(考虑一下试图找出Python 检查目录是否为(文件系统)根目录,python,Python,我有一个脚本,它搜索包含特定文件的目录,从当前目录开始,沿着树向上搜索(考虑一下试图找出.git目录的位置) 我的方法如下所示: def getDir(self,cwd): path = os.path.abspath(cwd) if not os.path.isdir(path): raise RuntimeError("getDir should not be run on files") if FILE in os.listdir(path): return p
.git
目录的位置)
我的方法如下所示:
def getDir(self,cwd):
path = os.path.abspath(cwd)
if not os.path.isdir(path):
raise RuntimeError("getDir should not be run on files")
if FILE in os.listdir(path):
return path
parent = os.path.join(path, os.path.pardir)
if os.access(parent, os.R_OK) and os.access(parent, os.X_OK):
return self.getDir(parent)
else
return None
现在这个方法的问题是,如果它找不到目录,它会循环(并最终导致堆栈溢出),因为显然加入/
和。
会再次给你/
。我试着将path
与parent
或他们的repr
进行比较,但没有成功(它们总是不同的)。我现在的解决方法是在递归方法中包含一个深度计数器,并在某个随机最大阈值处停止
因此,我的问题是,是否有可靠的跨平台方法来检查我是否已到达文件系统的根目录?我认为您无法通过可移植的方式确定它是否是文件系统根目录,然而,我建议对当前目录和计算的父目录进行调用,并比较它们是否相同——这意味着你正在旋转轮子,没有继续的必要 例如:
>>> os.path.realpath('/usr/bin/..')
'/usr'
>>> os.path.realpath('/usr/bin/../..')
'/'
>>> os.path.realpath('/usr/bin/../../..')
'/'
>>> os.path.realpath('/..')
'/'
这在Linux上适用于我们。但是,不确定Windows:
def _find_root(start, stop, func=os.path.exists):
"""Search up the start hierarchy for stop; return None at the FS root.
Uses func() to determine if stop exists; default is os.path.exists().
"""
if func(os.path.join(start, stop)):
return start
else:
if os.path.samefile(start, os.path.dirname(start)):
return None
else:
return _find_root(os.path.dirname(start), stop)
我们在调用此函数时使用os.path.normpath(start)。我不完全确定它在所有平台上是否可靠,但如果os.path.dirname(path)=path,则路径似乎是根。它对windows共享有效,但并不表示共享是根。。。它认为\\server是根目录。老实说,我觉得这更有道理。@Nacitarseave你可能是对的。将\\server视为根目录确实更有意义,但实际用处不大,因为通过执行“list dir”的常规工具枚举\\server的内容几乎不实际。如果路径包含“.”元素,例如@FatalError的答案中的元素,则此答案不起作用。
def _find_root(start, stop, func=os.path.exists):
"""Search up the start hierarchy for stop; return None at the FS root.
Uses func() to determine if stop exists; default is os.path.exists().
"""
if func(os.path.join(start, stop)):
return start
else:
if os.path.samefile(start, os.path.dirname(start)):
return None
else:
return _find_root(os.path.dirname(start), stop)