Home >Backend Development >Python Tutorial >How Can Python Extract Filenames Reliably Across Different Operating Systems?
Extracting Filenames Across Operating Systems with Python
When working with file paths, it's often necessary to extract the filename alone. However, paths can vary significantly depending on the operating system.
Desired Output:
Regardless of the operating system or path format, retrieve the following filename:
c
Solution:
Python's os module provides a convenient function for this task:
import os print(os.path.basename(your_path))
Note:
filepath = "C:\my\path\to\file.txt" os.path.basename(filepath) # Output: 'C:\my\path\to\file.txt'
The above is the detailed content of How Can Python Extract Filenames Reliably Across Different Operating Systems?. For more information, please follow other related articles on the PHP Chinese website!