-2

Is there any efficient way to select the last characters of a string file Name until there's a Slash / in Python?

For example, I got the following file Name:

File=r"C:\Users\folder1\folder2\folder3/fileIwanttoget.txt"

I would like to select only the string:

string=fileIwanttoget.txt

Independently of the number of characters that this file name has.

Lpng
  • 109
  • 1
  • 8
  • Use `split()`, i.e. `File.split("/")[-1]` – Henry Yik Aug 06 '19 at 07:50
  • 4
    Possible duplicate of [How to extract the file name from a file path?](https://stackoverflow.com/questions/45113157/how-to-extract-the-file-name-from-a-file-path) – Sayse Aug 06 '19 at 07:52

3 Answers3

3

pathlib is a modern approach to path handling and makes these tasks easy:

from pathlib import Path

f = Path("C:\Users\folder1\folder2\folder3/fileIwanttoget.txt")
f.name

fileIwanttoget.txt

Also, when you have a Path object you can open it directly:

from pathlib import Path

f = Path("C:\Users\folder1\folder2\folder3/fileIwanttoget.txt")
with f.open('r', encoding='utf8') as file_in:
    process(file_in)



monkut
  • 42,176
  • 24
  • 124
  • 155
2

You should use the python libraries that deal with file paths. The os.path is a good place to look into it.

from os.path import basename
string=basename(File)
user7440787
  • 831
  • 7
  • 22
1

If you simply want to split your string, you could do:

file_name = r"C:\Users\folder1\folder2\folder3/fileIwanttoget.txt"

ending = file_name.split('/')[-1]
print(ending)
# fileIwanttoget.txt

See the documentation on .split(). If you prefer working directly with paths, you should consider monkuts answer.

trotta
  • 1,232
  • 1
  • 16
  • 23
  • not the best solution if you run the code in a different operating system – user7440787 Aug 06 '19 at 07:57
  • What is that supposed to mean? – trotta Aug 06 '19 at 08:02
  • It works in this particular example but if you would have a pure windows path `r"C:\Users\folder1\folder2\folder3\fileIwanttoget.txt"` your solution will stop working. `os.path` or `pathlib` suggested by @monkut can deal with OS specific path representations – user7440787 Aug 06 '19 at 08:05
  • Valid point. However, OP was specifically asking how to split the string in his question (on `/`). Moreover, when working with paths you should be using the built-in `pathlib` package instead of `os` from python 3.4 on. – trotta Aug 06 '19 at 08:10