Separating File Name and Directory from a Path in Python: How to Use os.path.split

In programs handling file paths, operations like “extracting just the filename from a full path” or “getting the parent directory path excluding the filename” are frequent. Python’s standard library os.path module provides the split() function to easily divide a path into the “tail” (end part) and the “head” (part before it).

This article explains the basic behavior of os.path.split() and points to note when the path ends with a separator.


目次

Basics of os.path.split()

os.path.split() splits the path string passed as an argument into a tuple containing the following two elements:

  • head: The directory path excluding the last element.
  • tail: The last element (filename or last directory name).

Syntax:

import os

head, tail = os.path.split(path_string)

Specific Usage Example: Splitting a File Path

Here is an example of splitting a common path containing a file.

import os

# Sample file path
# (Separators are '\' on Windows and '/' on Mac/Linux)
file_path = os.path.join("documents", "reports", "monthly.csv")

print(f"Original Path: {file_path}")

# Split the path
directory, filename = os.path.split(file_path)

print(f"Directory (head): {directory}")
print(f"Filename (tail):  {filename}")

Output (Windows):

Original Path: documents\reports\monthly.csv
Directory (head): documents\reports
Filename (tail):  monthly.csv

As you can see, it cuts cleanly at the last separator.


[Important] When the Path Ends with a Separator

The point requiring the most caution when using os.path.split() is when the path ends with a separator (/ or \). In this case, the tail (end part) becomes an empty string "".

import os

# Directory path ending with a separator
dir_path_with_sep = os.path.join("backup", "data") + os.sep

print(f"Original Path: {dir_path_with_sep}")

head, tail = os.path.split(dir_path_with_sep)

print(f"head: '{head}'")
print(f"tail: '{tail}'")

Output (Windows):

Original Path: backup\data\
head: 'backup\data'
tail: ''

Intuitively, you might expect to get “data”, but actually, “everything after the last separator (which is empty)” is determined as the tail. If you want to get the last directory name, you need to remove the separator beforehand using .rstrip(os.sep) or similar methods.


Supplement: Getting Only One Part

If you don’t need both split values and only want “just the filename” or “just the directory path,” using dedicated functions makes the code easier to read.

  • os.path.basename(path): Returns only the tail.
  • os.path.dirname(path): Returns only the head.
path = os.path.join("images", "photo.jpg")

# Same result as tail
print(os.path.basename(path))  # -> photo.jpg

# Same result as head
print(os.path.dirname(path))   # -> images

Summary

  • os.path.split() splits a path into a tuple (head, tail).
  • head is the directory part, and tail is the last filename (or folder name).
  • If the path ends with a separator, tail becomes an empty string.
  • If you only need one part, consider using os.path.basename() or os.path.dirname().
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次