close

How to get only the name of the path with python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get only the name of the path with python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get only the name of the path with python?

  1. How to get only the name of the path with python?

    In Python 3.4+, you can use the pathlib module (included in Python's standard library):

  2. get only the name of the path with python

    In Python 3.4+, you can use the pathlib module (included in Python's standard library):

Method 1

In Python 3.4+, you can use the pathlib module (included in Python’s standard library):

>>> from pathlib import Path
>>> p = Path("/home/user/Downloads/repo/test.txt")
>>> print(p.stem)
test
>>> print(p.name)
test.txt

Method 2


It seems that you’re either looking for os.path.basename or os.path.splitext:

>>> import os.path
>>> os.path.basename("/var/log/err.log")
'err.log'
>>> os.path.splitext(os.path.basename("/var/log/err.log"))
('err', '.log')
>>> os.path.splitext(os.path.basename("/var/log/err.log"))[0]
'err'
>>>

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read