Approach 1: Using os.path.splitext
Using 'os.path.splitext' method, we can get the file extension.
‘splitext’ method split a path in root and extension. The extension is everything starting at the last dot in the last pathname component; the root is everything before that. It is always true that root + ext == p.
get_file_extension.py
import os
file_path = '/Users/Shared/poi/xls/test.xlsx'
file_name, file_extension = os.path.splitext(file_path)
print('file_name -> ', file_name)
print('file_extension -> ', file_extension)
Output
file_name -> /Users/Shared/poi/xls/test file_extension -> .xlsx
Approach 2: Using 'pathlib.Path().suffix'
get_file_extension_2.py
import pathlib
file_path = '/Users/Shared/poi/xls/test.xlsx'
file_extension = pathlib.Path(file_path).suffix
print('file_extension -> ', file_extension)
Output
file_extension -> .xlsx
No comments:
Post a Comment