[英]How to get the path of a sub folder under root directory of the project in python?
[英]How to split and separate root directory and sub directories from the path in python
列表中的路徑:
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)
甚至嘗試將路徑轉換為原始字符串,但沒有成功,即使我無法用任何其他字符替換 '/'
預期 output:
['3rdParty','metrics-server']
['3rdParty','node-problem-detector']
['3rdParty','oci-cloud\test']
['static-analysis', 'python-dependency-check\tests\unit\test_dockerfiles\real\kibana']
使用pathlib
,您應該執行以下操作。
這使用.parts
屬性將path.parent
可靠地拆分為組件。 您不應該假設目錄分隔符。
然后,通過將路徑傳遞回 pathlib.Path 來重構路徑的pathlib.Path
。
from pathlib import Path
for path in pathlist:
parts = path.parent.parts
res = [parts[0], str(Path(*parts[1:]))]
print(res)
在 Windows 的情況下,這應該為您提供所需的 output:
['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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.