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.
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)
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.