Get the File Name From the File Path in Python

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

Leave a Reply