Get Extension of File in Python

Python Program to Get an Extension of File Using splittext()

# Python Program to Get an Extension of File Using splittext()

# importing os module
import os

# this will return a tuple of root and extension
split_tup = os.path.splitext('file.txt')
print(split_tup)

# extract the file name and extension
file_name = split_tup[0]
file_extension = split_tup[1]

print("File Name: ", file_name)
print("File Extension: ", file_extension)

Output:

('file', '.txt')
File Name:  file
File Extension:  .txt

Python Program to Get an Extension of File Using pathlib

# Python Program to Get an Extension of File Using pathlib

# importing pathlib module
import pathlib

# function to return the file extension
file_extension = pathlib.Path('test.txt').suffix
print("File Extension: ", file_extension)

Output:

File Extension:  .txt

About The Author

Leave a Reply