Get file extension in Python

In this topic, we will learn what file extension is in Python and how to get file extension in Python. a file extension is the suffix at the end of a file name that indicates its file type.  for example:-

.py: This extension is used for Python source code files.

.pyc: This extension is used for bytecode files, which are created when Python code files are compiled into a bytecode.

Get file extension in Python

To get file extension in Python we use the os module. The os module is a built-in module. It allows you to perform various operations.  os model helps to handle directories to extract data and copy or extract extensions from file paths. Here is an example:-

#Add.py
a = 14
b =25
c = a+b
print("Add is " ,c)
Output :- Add is 39

in this example, we create a Python file whose name is Add.py. The path of this Python file in the local machine C:/Users/kucha/PycharmProjects/pythonProjectAdd. And we create another Python file to extract the extension of the file. file name Get_extension.py.Here is the code.

#Get_extension.py
import os
file_ext=os.path.splitext("C:/Users/kucha/PycharmProjects/pythonProjectAdd.py")
print(file_ext)
print(file_ext[1])
Output:-Output:-('C:/Users/kucha/PycharmProjects/pythonProjectAdd', '.py')
.py

Explanation:-

  1. we create another Python file and the name is Get_extension.py This Python will extract the Add.py file. using os module
  2. we use os. path to extract.
  3. The path C:/Users/kucha/PycharmProjects/pythonProjectAdd.py  is to convert into a tuple we use splitext. C:/Users/kucha/PycharmProjects/pythonProjectAdd.py  store in file_ext  variable.
  4. print the path with the help of the print(file_ext) method.C:/Users/kucha/PycharmProjects/pythonProjectAdd.py. But we find only the extension of this path.
  5. so we can use the  file_ext[1] .in the path of index value 0 is  C:/Users/kucha/PycharmProjects/pythonProjectAdd     and 1  is .py
  6. Here is all the explanation of this  Get file extension in Python topic.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top