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 while Loop
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Errors and Built-in Exceptions
Python Matrices and NumPy Arrays
Python String istitle()
Python Program to Create a Long Multiline String
Python frozenset()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Set issuperset()
Python Program to Check Prime Number
Python delattr()
Python Program to Safely Create a Nested Directory
Python Program to Illustrate Different Set Operations
Python Anonymous / Lambda Function
Python Program to Add Two Numbers
Python Dictionary
Python String translate()
Python Numbers, Type Conversion and Mathematics
Python Program to Convert Celsius To Fahrenheit
Python frozenset()
Python String title()
Python globals()
Python int()
Python Program to Check If a String Is a Number (Float)
Python String startswith()
Python Program to Get the Class Name of an Instance
Python any()
Python Program to Print the Fibonacci sequence
Python Functions
Python Program to Remove Punctuations From a String
Python chr()
Python Program to Check the File Size