-1

I want to get the substring from a path from the end to a certain character, take for example the following path:

my_path = "/home/Desktop/file.txt"

My intention is to do something like:

my_path.substring(end,"/")

So I can get the name of the file that is located between the end of the string and the character "/", in this case "file.txt"

L RodMrez
  • 137
  • 8
  • Have you had a look at the `os.path` module, specifically the [`os.path.basename`](https://docs.python.org/3/library/os.path.html#os.path.basename) function? – Kendas Nov 16 '18 at 12:30
  • Use `pathlib`. `from pathlib import Path; Path("/home/Desktop/file.txt").name == "file.txt"`. – erip Nov 16 '18 at 12:33

2 Answers2

1

The easiest approach, IMHO, would be to split the string:

filename = my_path.split('/')[-1]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

use the os.path.basename for this

In [1]: import os

In [2]: os.path.basename('/home/Desktop/file.txt')
Out[2]: 'file.txt'
Albin Paul
  • 3,330
  • 2
  • 14
  • 30