Extracting extension from filename in Python
You can extract the file extension from a file name in Python by using the os.path
module. Here's an example of how you can do it:
import os
# Get the file name
filename = "document.txt"
# Extract the file extension
extension = os.path.splitext(filename)[1]
# Print the file extension
print(extension)
This will output .txt
, which is the file extension.
Alternatively, you can use the pathlib
module to extract the file extension. Here's an example of how you can do it:
from pathlib import Path
# Get the file name
filename = "document.txt"
# Extract the file extension
extension = Path(filename).suffix
# Print the file extension
print(extension)
This will also output .txt
, which is the file extension.