Python Forum
extract last word from path.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
extract last word from path.
#1
Hi Team,

how to get last word from path.
split and get last folder name.

path = "D:\Python\sample_folder\data"

Expected output ---> Data



Thanks
mg
Reply
#2
One way is
path = 'D:\Python\sample_folder\data'
print(path)
path = path.split('\\')
folder = path[len(path)-1]
print(f'output -> {folder}')
Output:
output -> data
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
I usually simply split and slice:
path = "D:\Python\sample_folder\data"
lastword = path.split('\\')[-1]
print(lastword)
Output:
>>> path = "D:\Python\sample_folder\data" >>> lastword = path.split("\\")[-1] >>> print(lastword) data >>>
Reply
#4
Hi Larz60,

Thanks for your help.

one more query here, if i want data from data.txt
below code gives output, is there alternate solution.

path = "D:\Python\sample_folder\data.txt"
lastword = path.split('\\')[-1]
lastword = lastword.split('.')[-0]
print(lastword)
output - Data
Reply
#5
Or you could use Path from pathlib

from pathlib import Path

path = Path(r'D:\Python\sample_folder\data.txt')
long_filename = Path(r'D:\Python\sample_folder\This is a really big filename.txt')

print("path name:", path.name)
print("path stem:", path.stem)
print("path suffix:", path.suffix)

last_word = long_filename.stem.split()[-1]
print("Last word from big filename:", last_word)
Output:
path name: data.txt path stem: data path suffix: .txt Last word from big filename: filename
Larz60+ likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  extract substring from a string before a word !! evilcode1 3 554 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,225 Sep-09-2021, 01:25 PM
Last Post: Yoriz
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,519 Aug-12-2021, 04:25 PM
Last Post: palladium
  How to extract a single word from a text file buttercup 7 3,614 Jul-22-2020, 04:45 AM
Last Post: bowlofred
  Python Speech recognition, word by word AceScottie 6 16,032 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  Extract Httponly, Secure, domain and path from a cookie randeniyamohan 0 1,681 Jan-26-2020, 04:59 PM
Last Post: randeniyamohan
  print a word after specific word search evilcode1 8 4,868 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,781 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908
  difference between word: and word[:] in for loop zowhair 2 3,688 Mar-03-2018, 07:24 AM
Last Post: zowhair

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020