我有一个路径列表,我需要以便携方式提取每个路径的第一个元素, 我该怎么做?
['/abs/path/foo',
'rel/path',
'just-a-file']
到
['abs', 'rel', 'just-a-file']
提前致谢 奥利
答案 0 :(得分:6)
In [69]: import os
In [70]: paths
Out[70]: ['/abs/path/foo', 'rel/path', 'just-a-file']
In [71]: [next(part for part in path.split(os.path.sep) if part) for path in paths]
Out[71]: ['abs', 'rel', 'just-a-file']
答案 1 :(得分:2)
有一个库调用以独立于平台的方式处理拆分路径,但它只分为两部分:
import os.path
def paths(p) :
head,tail = os.path.split(p)
components = []
while len(tail)>0:
components.insert(0,tail)
head,tail = os.path.split(head)
return components
for p in ['/abs/path/foo','rel/path','just-a-file'] :
print paths(p)[0]
答案 2 :(得分:1)
使用更新的pathlib方法...
import PurePath from pathlib
import os
# Separates the paths into parts and prints to the console...
def print_path_parts(path: str):
path = PurePath(path)
parts = list(path.parts)
# From your description, looks like you don't want the root.
# Pop it off.
if parts[0] == os.sep:
parts.pop(0)
print(parts)
# Array of path strings...
paths = ['/abs/path/foo',
'rel/path',
'just-a-file']
# For each path, print parts to the console
for path in paths:
print_path_parts(path)
输出:
['abs', 'path', 'foo']
['rel', 'path']
['just-a-file']
答案 3 :(得分:-5)
为什么不使用正则表达式?
>>> import re
>>> paths = ['/abs/path/foo',
... 'rel/path',
... 'just-a-file']
>>>
>>> [re.match(r'\/?([^\/]+)', p).groups()[0] for p in paths]
['abs', 'rel', 'just-a-file']
和Windows:
>>> paths = [r'\abs\path\foo',
... r'rel\path',
... r'just-a-file',
... r'C:\abs\path\foo',
... r'C:rel\path',
... r'C:just-a-file']
>>>
>>> [re.match(r'(?:[A-Za-z]:)?\\?([^\\]+)', p).groups()[0] for p in paths]
['abs', 'rel', 'just-a-file', 'abs', 'rel', 'just-a-file']