列表中的路径:
pathlist=[3rdParty\metrics-server\Dockerfile,
3rdParty\node-problem-detector\Dockerfile,
3rdParty\oci-cloud\test\Dockerfile,
static-analysis\python-dependency-check\tests\unit\test_dockerfiles\real\kibana\Dockerfile]我试过了
for path in pathlist:
p=path.parent #removes file name from path
p=p.split('\', 1)我甚至尝试过将路径转换为原始字符串,但不起作用,甚至我不能用任何其他字符替换'/‘
预期输出:
['3rdParty','metrics-server']
['3rdParty','node-problem-detector']
['3rdParty','oci-cloud\test']
['static-analysis', 'python-dependency-check\tests\unit\test_dockerfiles\real\kibana']发布于 2021-01-19 19:34:37
使用pathlib,您应该执行如下操作。
它使用.parts属性可靠地将path.parent拆分成多个组件。您不应该使用目录分隔符。
然后,通过将其传递回pathlib.Path来重建路径的其余部分。
from pathlib import Path
for path in pathlist:
parts = path.parent.parts
res = [parts[0], str(Path(*parts[1:]))]
print(res)对于Windows,这将为您提供所需的输出:
['3rdParty', 'metrics-server']
['3rdParty', 'node-problem-detector']
['3rdParty', 'oci-cloud\test']
['static-analysis', 'python-dependency-check\tests\unit\test_dockerfiles\real\kibana']在*NIX的情况下,你会得到这样的结果:
['3rdParty', 'metrics-server']
['3rdParty', 'node-problem-detector']
['3rdParty', 'oci-cloud/test']
['static-analysis', 'python-dependency-check/tests/unit/test_dockerfiles/real/kibana']https://stackoverflow.com/questions/65790322
复制相似问题