Table of Contents
In this example, you will learn to get the file name from the file path.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using os module
import os
# file name with extension
file_name = os.path.basename('/root/file.ext')
# file name without extension
print(os.path.splitext(file_name)[0])
Output
file
basename() gives the name of the last file/folder of the path, whereas splitext() splits the file name into filename and extension.
import os print(os.path.splitext(file_name))
Output
('file', '.ext')
2. Example 2: Using Path module
from pathlib import Path
print(Path('/root/file.ext').stem)
Output
file
Using stem attribute of Path module, the file name can be extracted as shown above.
It works for python 3.4 and above.
Related posts:
Python setattr()
Python Program to Find HCF or GCD
Python issubclass()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python pass statement
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Custom Exceptions
Python divmod()
Python String index()
Python List append()
Python Program to Catch Multiple Exceptions in One Line
Python Program to Check if a Key is Already Present in a Dictionary
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python String translate()
Python Program to Convert Two Lists Into a Dictionary
Python Set discard()
Python Get Current time
Python Program to Convert Kilometers to Miles
Python any()
Python Closures
Python Program to Print Colored Text to the Terminal
Python Program to Count the Number of Digits Present In a Number
Python float()
Python Program to Slice Lists
Python Program to Display Calendar
Python String rindex()
Python bytearray()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python List copy()
Python Dictionary pop()
Python Machine Learning - Sebastian Raschka