Python Get Directory, File Name and Extension from an Absolute Path – Python Tutorial

By | August 20, 2019

When operating files in python, there some basic operations we shoud notice, for example, how to get directory, file name and file extension. In this tutorial, we will introduce how to get these file information.

python file operation

Import library

import os

Create an absolute path

file = r'E:\workspace-python\examples\'

Get directory name

dirname = os.path.dirname(file)

The output is:


Get file name

basename = os.path.basename(file)

The output is:

Get file name without file extension

info = os.path.splitext(basename)
filename = info[0]

The file name is:

Get file extension
extend = info[1]

The file extension is:


Here we can build a function to get these basic file information.

def getFilePathInfo(absolute):
    dirname = os.path.dirname(absolute)
    basename = os.path.basename(absolute)
    info = os.path.splitext(basename)
    filename = info[0]
    extend = info[1]
    return dirname, filename, extend

How to use?

info = getFilePathInfo(file)

The file information is:

('E:\\workspace-python\\examples', 'test', '.py')

Leave a Reply

Your email address will not be published. Required fields are marked *