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 max()
Python Directory and Files Management
Python callable()
Python Program to Find the Factors of a Number
Python Program to Shuffle Deck of Cards
Python Program to Copy a File
Python Program to Check if a Number is Odd or Even
Python Global Keyword
Python String isdecimal()
Python Program to Get a Substring of a String
Python property()
Python hash()
Python String rfind()
Python Program to Access Index of a List Using for Loop
Python Recursion
Python String encode()
Python Program to Return Multiple Values From a Function
Deep Learning in Python - LazyProgrammer
Python sum()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python String swapcase()
Python list()
Python File I/O Operation
Python Program to Compute all the Permutation of the String
Python Program to Find HCF or GCD
How to Get Started With Python?
Python oct()
Python Generators
Python List extend()
Python hasattr()
Python String join()
Python memoryview()