os.path.basename() method in Python is used to extract the final part of a file path. This final part can be a file name or the last folder name. It is commonly used when working with file paths to get only the name without the full path.
import os
p = "/home/user/file.txt"
r = os.path.basename(p)
print(r)
Output
file.txt
Explanation:
- p = "/home/user/file.txt" stores the full file path.
- r = os.path.basename(p) extracts the last part of the path.
Syntax
os.path.basename(path)
- Parameter: path - A file path from which the base name is extracted.
- Return Value: Returns a string containing the file name or last folder name.
Examples
Example 1: This example extracts the file name from a relative path. This is useful when working with local project files.
import os
p = "data.csv"
r = os.path.basename(p)
print(r)
Output
data.csv
Explanation:
- p = "data.csv" stores relative file path.
- r = os.path.basename(p) extracts file name.
Example 2: This example extracts the last folder name from a directory path.
import os
p = "/home/user/Documents"
r = os.path.basename(p)
print(r)
Output
Documents
Explanation:
- p = "/home/user/Documents" stores folder path.
- r = os.path.basename(p) extracts folder name.
Example 3: This example shows what happens when the path ends with a trailing slash. It helps understand how basename() behaves with folder paths ending in /.
import os
p = "/home/user/Documents/"
r = os.path.basename(p)
print(r)
Output
Explanation:
- p = "/home/user/Documents/" stores a folder path that ends with a slash.
- r = os.path.basename(p) returns empty string because the last part after / is empty.