Python Program to Get the File Name From the File Path Using split()
# Python Program to Get the File Name From the File Path Using split()
# file path
file_path = "C:/Users/Documents/file.txt"
# split function
file_name = file_path.split("/")[-1]
print(file_name)
Output
file.txt
Python Program to Get the File Name From the File Path Using OS Module
# Python Program to Get the File Name From the File Path Using OS Module
# importing OS module
import os
# path
file_path = "C:/Users/User1/Documents/file1.txt"
# os.path.basename function to get the filename from the path
full_name = os.path.basename(file_path)
# os.path.splitext function to get filename without extension
file_name = os.path.splitext(full_name)
print(full_name)
print(file_name[0])
Output
file1.txt
file1
Python Program to Get the File Name From the File Path Using pathlib
# Python Program to Get the File Name From the File Path Using pathlib
# importing pathlib module
from pathlib import Path
# path
file_path = "C:/Users/Documents/file_one.txt"
# path function with name attribute to give file name with extension
full_name = Path(file_path).name
# path function with stem attribute to give file name without extension
file_name = Path(file_path).stem
print(full_name)
print(file_name)
Output:
file_one.txt
file_one
About The Author
Shailendra Bramhvanshi, Founder at Techaroha Solutions Private Limited and CEO at Newtum Solutions Private Limited. BlockChain Experts with 12 years of IT Experience in of all aspects of running Organization and Project Management. I have created different coins to help the business to bring more trust. Recently deployed a stable coin in India TrueINR and working on few cryptocurrency exchanges. My Team is being rated as a top 10 blockchain service provider in India by Silicon India