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 time Module
Python Program to Generate a Random Number
Python Program to Check Armstrong Number
Python bytes()
Python Program to Find Factorial of Number Using Recursion
Python String zfill()
Python Get Current time
Python Program to Print Hello world!
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Find the Square Root
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Multiple Inheritance
Python Set add()
Python String join()
Python Program to Extract Extension From the File Name
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Statement, Indentation and Comments
Python List pop()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Objects and Classes
Python Global Keyword
Python strptime()
Python Generators
Python Program to Find the Size (Resolution) of a Image
Python Closures
Python Program to Count the Number of Digits Present In a Number
Python List reverse()
Python RegEx
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python String rstrip()
Python Program to Check If Two Strings are Anagram
Python Program to Compute all the Permutation of the String