Get the filename, directory, extension from a path string in Python | note.nkmk.me (2024)

In Python, you can get the filename (basename), directory (folder) name, and extension from a path string or join the strings to generate the path string with the os.path module in the standard library.

Contents

  • Difference in path separator by OS
  • Get the filename (basename) from a path: os.path.basename()
    • Filename with extension
    • Filename without extension
  • Get the directory (folder) name from a path: os.path.dirname()
  • Get the file and directory name pair: os.path.split()
    • Notes on when a path string indicates a directory
  • Get the extension: os.path.splitext()
    • Create a path string with a different extension
    • Get the extension without dot (period)
    • Examples of cases like .tar.gz
  • Create a path string by combining the file and directory names: os.path.join()
    • Create a path string for another file in the same directory
  • Use different OS formats
  • Examples for Windows
    • Backslash and raw string
    • Examples of getting file name, folder name, extension
    • Get and join a drive letter: os.path.splitdrive()

Use the following path string as an example.

import osfilepath = './dir/subdir/filename.ext'

The sample code below is running on a Mac. Examples for Windows are shown at the end.

This article explains how to obtain file and directory names from path strings. Refer to the following article if you want to obtain a list of file and directory names in a directory.

  • Get a list of file and directory names in Python

In Python 3.4 or later, you can also get the filename, directory (folder) name, extension, etc., with the pathlib module that treats paths as objects.

Difference in path separator by OS

The path separator varies depending on the OS. UNIX (including Mac) uses the slash /, while Windows uses the backslash \.

You can get the separator in the OS running Python with os.sep or os.path.sep.

print(os.sep)# /print(os.sep is os.path.sep)# True

Get the filename (basename) from a path: os.path.basename()

Use os.path.basename() to get the filename (basename) from a path string.

Filename with extension

os.path.basename() returns the filename with the extension.

filepath = './dir/subdir/filename.ext'basename = os.path.basename(filepath)print(basename)# filename.extprint(type(basename))# <class 'str'>

Filename without extension

You can get the filename without the extension with os.path.splitext() described later.

filepath = './dir/subdir/filename.ext'basename_without_ext = os.path.splitext(os.path.basename(filepath))[0]print(basename_without_ext)# filename

os.path.splitext() split at the last (right) dot .. If you want to split by the first (left) dot ., use split().

  • Split a string in Python (delimiter, line break, regex, and more)
filepath_tar_gz = './dir/subdir/filename.tar.gz'print(os.path.splitext(os.path.basename(filepath_tar_gz))[0])# filename.tarprint(os.path.basename(filepath_tar_gz).split('.', 1)[0])# filename

Get the directory (folder) name from a path: os.path.dirname()

Use os.path.dirname() to get the directory folder (name) from a path string.

filepath = './dir/subdir/filename.ext'dirname = os.path.dirname(filepath)print(dirname)# ./dir/subdirprint(type(dirname))# <class 'str'>

If you want to get only the directory name directly above the file, use os.path.basename().

subdirname = os.path.basename(os.path.dirname(filepath))print(subdirname)# subdir

Get the file and directory name pair: os.path.split()

Use os.path.split() to get both the file and directory (folder) name.

os.path.split() returns a tuple of filename returned by os.path.basename() and directory name returned by os.path.dirname().

filepath = './dir/subdir/filename.ext'base_dir_pair = os.path.split(filepath)print(base_dir_pair)# ('./dir/subdir', 'filename.ext')print(type(base_dir_pair))# <class 'tuple'>print(os.path.split(filepath)[0] == os.path.dirname(filepath))# Trueprint(os.path.split(filepath)[1] == os.path.basename(filepath))# True

You can unpack tuple to assign to each variable.

  • Unpack a tuple and list in Python
dirname, basename = os.path.split(filepath)print(dirname)# ./dir/subdirprint(basename)# filename.ext

Use os.path.join() described later to rejoin the file and directory names.

Notes on when a path string indicates a directory

Note that the result will differ for a path string indicating a directory (folder) based on the presence or absence of a separator at the end.

No separator at the end:

dirpath_without_sep = './dir/subdir'print(os.path.split(dirpath_without_sep))# ('./dir', 'subdir')print(os.path.basename(dirpath_without_sep))# subdir

If there is a separator at the end, use os.path.dirname() and os.path.basename() to get the bottom folder name.

dirpath_with_sep = './dir/subdir/'print(os.path.split(dirpath_with_sep))# ('./dir/subdir', '')print(os.path.basename(os.path.dirname(dirpath_with_sep)))# subdir

Get the extension: os.path.splitext()

Use os.path.splitext() to get the extension.

os.path.splitext() splits the extension and others and returns it as a tuple. The extension contains the dot ..

filepath = './dir/subdir/filename.ext'root_ext_pair = os.path.splitext(filepath)print(root_ext_pair)# ('./dir/subdir/filename', '.ext')print(type(root_ext_pair))# <class 'tuple'>

You can concatenate with the + operator to return the original path string.

  • Concatenate strings in Python (+ operator, join, etc.)
root, ext = os.path.splitext(filepath)print(root)# ./dir/subdir/filenameprint(ext)# .extpath = root + extprint(path)# ./dir/subdir/filename.ext

Create a path string with a different extension

To create a path string with only the extension changed from the original, concatenate the first element of the tuple returned by os.path.splitext() with any extension.

filepath = './dir/subdir/filename.ext'other_ext_filepath = os.path.splitext(filepath)[0] + '.jpg'print(other_ext_filepath)# ./dir/subdir/filename.jpg

Get the extension without dot (period)

If you want to get the extension without the dot (period) ., specify the second and subsequent strings with slice [1:].

  • How to slice a list, string, tuple in Python
filepath = './dir/subdir/filename.ext'ext_without_dot = os.path.splitext(filepath)[1][1:]print(ext_without_dot)# ext

Examples of cases like .tar.gz

Note that os.path.splitext() splits at the last (right) dot . as demonstrated in the previous example. Be cautious with extensions like .tar.gz.

filepath_tar_gz = './dir/subdir/filename.tar.gz'print(os.path.splitext(filepath_tar_gz))# ('./dir/subdir/filename.tar', '.gz')

If you want to split by the first (left) dot . in the file name, use the split() method of the string, but it doesn't work if the directory name also contains the dot..

print(filepath_tar_gz.split('.', 1))# ['', '/dir/subdir/filename.tar.gz']

After splitting with os.path.split(), apply the split() method of the string and join with os.path.join() described later.

The string returned by split() does not contain a delimiter, so be careful if you want to get an extension with a dot . like os.path.splitext().

dirname, basename = os.path.split(filepath_tar_gz)basename_without_ext, ext = basename.split('.', 1)path_without_ext = os.path.join(dirname, basename_without_ext)print(path_without_ext)# ./dir/subdir/filenameprint(ext)# tar.gzext_with_dot = '.' + extprint(ext_with_dot)# .tar.gz

Create a path string by combining the file and directory names: os.path.join()

Use os.path.join() to join file and directory names to create a new path string.

path = os.path.join('dir', 'subdir', 'filename.ext')print(path)# dir/subdir/filename.ext

Create a path string for another file in the same directory

If you want to create a path string for another file in the same directory of one file, use os.path.dirname() and os.path.join().

filepath = './dir/subdir/filename.ext'other_filepath = os.path.join(os.path.dirname(filepath), 'other_file.ext')print(other_filepath)# ./dir/subdir/other_file.ext

Use different OS formats

If you want to manipulate path strings in an OS format that is not the OS on which Python is currently running, import and use different modules instead of the os module.

  • UNIX (including current Mac): posixpath
  • Windows: ntpath
  • Macintosh 9 and earlier: macpath

Since each module has the same interface as os.path, you can change the os.path part of the sample code so far to their module names (such as ntpath).

Examples for Windows

The sample code below is running on Mac using the ntpath module mentioned above. When running on Windows, you can replace ntpath with os.path.

Backslash and raw string

The path separator in Windows is the backslash \.

To write a backslash in a string, you need to write two backslashes to escape. print() outputs one backslash.

import ntpathprint(ntpath.sep)# \print('\\')# \print(ntpath.sep is '\\')# True

source: os_ntpath.py

Using a raw string (r'xxx') simplifies writing a Windows path, as it allows you to write a backslash directly. Raw strings and normal strings have equal value.

file_path = 'c:\\dir\\subdir\\filename.ext'file_path_raw = r'c:\dir\subdir\filename.ext'print(file_path == file_path_raw)# True

source: os_ntpath.py

For more information about raw strings, see the following article.

  • Raw strings in Python

Examples of getting file name, folder name, extension

These examples also work on Windows.

print(ntpath.basename(file_path))# filename.extprint(ntpath.dirname(file_path))# c:\dir\subdirprint(ntpath.split(file_path))# ('c:\\dir\\subdir', 'filename.ext')

source: os_ntpath.py

Get and join a drive letter: os.path.splitdrive()

Use os.path.splitdrive() to get the drive letter. The sample code below uses ntpath.splitdrive().

os.path.splitdrive() splits the drive letter including the colon : and others.

print(ntpath.splitdrive(file_path))# ('c:', '\\dir\\subdir\\filename.ext')

source: os_ntpath.py

If you want to get only the drive letter, select the first character.

drive_letter = ntpath.splitdrive(file_path)[0][0]print(drive_letter)# c

source: os_ntpath.py

Be careful when joining drive characters.

If you pass it to os.path.join() as it is, it will not work.

print(ntpath.join('c:', 'dir', 'subdir', 'filename.ext'))# c:dir\subdir\filename.ext

source: os_ntpath.py

You can also specify os.sep (ntpath.sep in the sample code) for the argument of os.path.join() or add a separator to the drive letter.

print(ntpath.join('c:', ntpath.sep, 'dir', 'subdir', 'filename.ext'))# c:\dir\subdir\filename.extprint(ntpath.join('c:\\', 'dir', 'subdir', 'filename.ext'))# c:\dir\subdir\filename.ext

source: os_ntpath.py

Get the filename, directory, extension from a path string in Python | note.nkmk.me (2024)
Top Articles
Articles
Capital Loss Carryover: Definition, Rules, and Example
Devin Mansen Obituary
Custom Screensaver On The Non-touch Kindle 4
It may surround a charged particle Crossword Clue
Loves Employee Pay Stub
Euro (EUR), aktuální kurzy měn
Boomerang Media Group: Quality Media Solutions
How to know if a financial advisor is good?
Klustron 9
Mndot Road Closures
Wunderground Huntington Beach
Everything You Need to Know About Holly by Stephen King
Lonadine
Betonnen afdekplaten (schoorsteenplaten) ter voorkoming van lekkage schoorsteen. - HeBlad
Walthampatch
Tvtv.us Duluth Mn
Nordstrom Rack Glendale Photos
Why Should We Hire You? - Professional Answers for 2024
Lista trofeów | Jedi Upadły Zakon / Fallen Order - Star Wars Jedi Fallen Order - poradnik do gry | GRYOnline.pl
Raw Manga 1000
Trivago Myrtle Beach Hotels
Defending The Broken Isles
Ncal Kaiser Online Pay
Abga Gestation Calculator
Dreammarriage.com Login
2024 Ford Bronco Sport for sale - McDonough, GA - craigslist
Tds Wifi Outage
Honda Ruckus Fuse Box Diagram
Weapons Storehouse Nyt Crossword
Hell's Kitchen Valley Center Photos Menu
Game8 Silver Wolf
Wsbtv Fish And Game Report
Wal-Mart 2516 Directory
Wayne State Academica Login
SF bay area cars & trucks "chevrolet 50" - craigslist
Lbl A-Z
Windshield Repair & Auto Glass Replacement in Texas| Safelite
Saline Inmate Roster
18006548818
Cocorahs South Dakota
Unveiling Gali_gool Leaks: Discoveries And Insights
Www Craigslist Com Atlanta Ga
Cabarrus County School Calendar 2024
John M. Oakey & Son Funeral Home And Crematory Obituaries
Goats For Sale On Craigslist
The Nikki Catsouras death - HERE the incredible photos | Horror Galore
Fluffy Jacket Walmart
Huntsville Body Rubs
Minecraft: Piglin Trade List (What Can You Get & How)
Craigslist Charles Town West Virginia
Causeway Gomovies
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated:

Views: 6463

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.