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 Dictionary popitem()
Machine Learning with Python for everyone - Mark E.Fenner
Python Global Keyword
Python Program to Get Line Count of a File
Python Dictionary pop()
Python String lower()
Python bytes()
Python List clear()
Python Generators
Python String isprintable()
Python Program to Count the Number of Digits Present In a Number
Python Function Arguments
Python String isalnum()
Python Program to Find the Factorial of a Number
Python Tuple
Python Program to Check If a String Is a Number (Float)
Python String index()
Python String isalpha()
Python divmod()
Python exec()
Python for Loop
Python List insert()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python globals()
Python String format()
Python Program to Iterate Over Dictionaries Using for Loop
Python open()
Python Object Oriented Programming
Python Dictionary
Python Set issuperset()
Python String split()
Python Program to Shuffle Deck of Cards