In Python, extracting the file name from a file path can be tricky, especially when considering different operating systems like Windows, macOS, or Linux, which use different path formats. Fortunately, Python’s built-in os.path module can handle these differences automatically. Here’s how you can do it:
import os # Example file paths windows_path = r"C:\Users\Example\Documents\file.txt" linux_path = "/home/example/documents/file.txt" mac_path = "/Users/example/Documents/file.txt" # Extract file name using os.path.basename print("File name from Windows path:", os.path.basename(windows_path)) print("File name from Linux path:", os.path.basename(linux_path)) print("File name from macOS path:", os.path.basename(mac_path))
os.path.basename():
This function from the os.path module extracts the base name (file name) from a full file path, regardless of the operating system. It works by stripping the path components and returning just the final segment, which is typically the file name.
os.path.basename() is cross-platform, which makes it a reliable choice for file name extraction in Python. It takes care of the differences between path formats and works seamlessly on both UNIX-like systems (Linux/macOS) and Windows.
This method also avoids errors that might arise if you manually attempt to split the path string using different delimiters for each OS.
If you prefer a more modern approach, you can also use the pathlib module, which is available in Python 3.4 and later.
from pathlib import Path # Example file paths windows_path = Path(r"C:\Users\Example\Documents\file.txt") linux_path = Path("/home/example/documents/file.txt") mac_path = Path("/Users/example/Documents/file.txt") # Extract file name using Path.name print("File name from Windows path:", windows_path.name) print("File name from Linux path:", linux_path.name) print("File name from macOS path:", mac_path.name)
Path.name: This returns the file name directly from the path object, handling the OS differences for you.