How can I get the last folder and the filename of a path in Python?
I am doing:
pre_l="/this/is/the/absolute/path/from_here/thefile.txt"
pt=os.path.join(".",os.path.basename(os.path.dirname(pre_l)),os.path.basename(pre_l))
Is there a simpler way?
CodePudding user response:
This is pretty easy with pathlib
- the parts
attribute breaks down the path components into a tuple. pathlib
was introduced with Python 3.4.
>>> from pathlib import Path
>>> p = Path("/this/is/the/absolute/path/from_here/thefile.txt")
>>> p.parts
('/', 'this', 'is', 'the', 'absolute', 'path', 'from_here', 'thefile.txt')
so this should give what you're looking for:
>>> "./" "/".join(p.parts[-2:])
'./from_here/thefile.txt'
CodePudding user response:
I recommend using the pathlib module specifically meant for handling paths, not regex.
from pathlib import Path, PurePath
p = Path('/this/is/the/absolute/path/from_here/thefile.txt')
x = p.parts[-2:]
p = PurePath(*x)
print(p) # from_here/thefile.txt
CodePudding user response:
Consider using re
import os, re
pre_l = "/this/is/the/absolute/path/from_here/thefile.txt"
pt = os.sep.join(['.'] re.split(r'[\//]', pre_l)[-2:])
CodePudding user response:
This is a solution I created when I was having the same problem
import platform
slashchr = '\\' if platform.system()=='Windows' else '/'
pre_l = "/this/is/the/absolute/path/from_here/thefile.txt"
temp_list = pre_l.split(slashchr)
pt = slashchr.join(temp_list[-2:])
Edit: This is essentially doing what @robopyjs 's answer is doing, but this solution is also taking in account the operating system
CodePudding user response:
There is a very simple way to do this, the idea is that:
- split the path with
/
- select the folder and file name
- join them with slash
Implementation:
pre_l="/this/is/the/absolute/path/from_here/thefile.txt"
pt = "./" "/".join(pre_l.split('/')[-2:]) #output: ./from_here/thefile.txt