KansaiRobot
KansaiRobot

Reputation: 9922

How to get only the last folder and filename of a path?

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?

Upvotes: 0

Views: 474

Answers (5)

Mark Mikealson
Mark Mikealson

Reputation: 29

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:])

Upvotes: 0

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24568

I recommend using the pathlib module specifically meant for handling paths, not regex.

from pathlib import Path
p = Path('/this/is/the/absolute/path/from_here/thefile.txt')
x = p.parts[-2:]
p = Path(*x)
print(p) # from_here/thefile.txt

Upvotes: 1

sj95126
sj95126

Reputation: 6908

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'

Upvotes: 1

random_hooman
random_hooman

Reputation: 2238

There is a very simple way to do this, the idea is that:

  1. split the path with /
  2. select the folder and file name
  3. 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

Upvotes: 1

Ming
Ming

Reputation: 479

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:])

Upvotes: 0

Related Questions