python get file name – How To Get Filename From A Path In Python?

python get file name Use Python ntpath Library, Use Python ntpath.basename(), Using os.path.basename() and Python Get Filename From Path Using os.path.split() Example.

python get file name

python get file name : Get Filename From Path in Python : Write a Python program to extract the filename from a given path. Extract the file name (base name): os.path.basename().

Use Python ntpath Library to Get the Filename From Path

Example

import ntpath
print(ntpath.basename("usr/temp/new/infinityknow"))

Result

infinityknow

Use Python ntpath.basename() to Get the Filename From Path

Example

import ntpath

print(ntpath.basename("r'usr/infinityknow\guestpost'"))

Result

infinityknow\guestpost

Don’t Miss : How To Increment The Filename If File Already Exists In PHP?

Read Also:  Top 33+ python interview questions and answers (PDF) for Freshers [2021 Latest]

Python Get Filename From Path Using os.path.basename()

Example 1

import os

print(os.path.basename("usr/pakainfo/guestpost"))

Result

guestpost

Example : 2

# in Linux
import os

print(os.path.basename("C:\\demo\\pakainfo.jpg"))

Result

C:\\demo\\pakainfo.jpg

Python Get Filename From Path Using os.path.split()

Example

import os

head, tail = os.path.split("/Users/infinityknow/Uploads")
print(head)
print(tail)

Result

/Users/infinityknow
Uploads

I hope you get an idea about python get file name.

I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.