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 Machine Learning Eqution Reference - Sebastian Raschka
Python String rjust()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Remove Duplicate Element From a List
Python max()
Python Program to Find the Sum of Natural Numbers
Intelligent Projects Using Python - Santanu Pattanayak
Python Set difference()
Python Set clear()
Python while Loop
Python Program to Compute the Power of a Number
Python Set discard()
Python Errors and Built-in Exceptions
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python dict()
Python oct()
Python String isalnum()
Python Program to Find ASCII Value of Character
Python String join()
Python Program to Append to a File
APIs in Node.js vs Python - A Comparison
Python String format_map()
Python format()
Python Program to Print the Fibonacci sequence
Python List count()
Python Program to Find the Square Root
Python String swapcase()
Python String title()
Python String rpartition()
Python Program to Get the Last Element of the List
Python String casefold()
Python Program to Randomly Select an Element From the List