gpt4 book ai didi

python - 查找路径的根

转载 作者:太空狗 更新时间:2023-10-29 22:04:58 27 4
gpt4 key购买 nike

我有一条路:

path = foo/bar/baz

我想确定基数是什么。在此示例中,它应该返回 “foo”

我试过几种方法:

root = re.search('(.+?)/(.+)', path).group(1)

paths = path.split('/')[0]
root = paths[0] if paths[0] or len(paths) <= 1 else '/'.join(paths[0:2])

def rootname(path):
head,tail = os.path.split(path)
if head != '':
return rootname(head)
else:
return path
root = rootname(path)

是否有更“Pythonic”的方式来访问根目录?

root = os.path.''rootname''(path)

最佳答案

>>> import os
>>> path = '/foo/bar/baz'
>>> path = path.lstrip(os.sep) # Get rid of leading "/" if any
>>> root = path[:path.index(os.sep)] if os.sep in path else path
>>> root
'foo'

关于python - 查找路径的根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13940319/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com