Pythonpath获取路径的最后一部分
Pythonpath get last part of path
我不想使用 pathlib,所以避免用它回答
aString = "/test/test1/test2/test3"
aString = os.path(astring.parts[1:])
我想得到 /test1/test2/test3 ,使用 import os 或 import os.path
如果你只能使用os
,这可能适合:
my_path = '/test1/test2/test3/test4'
os.path.sep.join(['']+my_path.split(os.path.sep)[2:])
请注意,它需要 2:
,因为根也会在拆分中,所以它只是将其添加回去。
另请注意,如果您的路径实际上是 /test1/test2/test3/test4
,那么 /test2/test3/test4
似乎是一个奇怪的值,因为它仍然从根开始 - 您可能想检查一下这是否真的是您需要的。
我不想使用 pathlib,所以避免用它回答
aString = "/test/test1/test2/test3"
aString = os.path(astring.parts[1:])
我想得到 /test1/test2/test3 ,使用 import os 或 import os.path
如果你只能使用os
,这可能适合:
my_path = '/test1/test2/test3/test4'
os.path.sep.join(['']+my_path.split(os.path.sep)[2:])
请注意,它需要 2:
,因为根也会在拆分中,所以它只是将其添加回去。
另请注意,如果您的路径实际上是 /test1/test2/test3/test4
,那么 /test2/test3/test4
似乎是一个奇怪的值,因为它仍然从根开始 - 您可能想检查一下这是否真的是您需要的。