To extract a file name from a path in a way that works across operating systems, use Python’s os.path or pathlib modules. For os.path, use os.path.basename(path). Example:
import os
file_name = os.path.basename(“/path/to/file.txt”)
print(file_name) # Output: file.txt
For pathlib, use the .name attribute:
from pathlib import Path
file_name = Path(“/path/to/file.txt”).name
print(file_name) # Output: file.txt
Both methods handle different path formats (Windows or Unix) automatically, ensuring compatibility across operating systems.