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 pop()
Python list()
Python Program to Convert Two Lists Into a Dictionary
Python max()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python String rindex()
Python Program to Measure the Elapsed Time in Python
Python oct()
Python Namespace and Scope
Python Modules
Python Program to Copy a File
Python Program to Get the Last Element of the List
Python del Statement
Python hash()
Deep Learning with Python - Francois Chollet
Python bin()
Python format()
Python Input, Output and Import
Python Program to Extract Extension From the File Name
Python String lstrip()
Python Program to Catch Multiple Exceptions in One Line
Python Tuple
Python Program to Create a Long Multiline String
Python String title()
Python Set intersection()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Deep Learning with Python - Francois Cholletf
Python String splitlines()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
How to Get Started With Python?
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...