22
loading...
This website collects cookies to deliver better user experience
splitext()
will take the path as an argument and return the tuple with filename and extension.import os
# returns tuple wit filename and extension
file_details = os.path.splitext('/home/usr/sample.txt')
print("File Details ",file_details)
# extract the file name and extension
file_name = file_details[0]
file_extension = file_details[1]
print("File Name: ", file_name)
print("File Extension: ", file_extension)
File Details ('/home/usr/sample', '.txt')
File Name: /home/usr/sample
File Extension: .txt
pathlib.path().suffix
method can be used to extract the extension of the given file path.import pathlib
# pathlib function which returns the file extension
file_extension = pathlib.Path('/home/usr/sample.txt').suffix
print("The given File Extension is : ", file_extension)
The given File Extension is : .txt
sample.tar.gz
* with multiple dots, and if you use the above methods, you will only get the last part of the extension, not the full extension.pathlib
module with suffixes
property which returns all the extensions as a list. Using that, we can join into a single string, as shown below.import pathlib
# pathlib function which returns the file extension
file_extension = pathlib.Path('/home/usr/sample.tar.gz').suffixes
print("File extension ", file_extension)
print("The given File Extension is : ", ''.join(file_extension))
File extension ['.tar', '.gz']
The given File Extension is : .tar.gz