Get the Filename and a Line Number in Python

Get the Filename and a Line Number in Python

Vaibhav Vaibhav Mar-29, 2022 Dec-28, 2021 Python Python File

When working on real-world applications or side projects, we often have to retrieve line numbers and filenames for debugging purposes. Generally, this is done to understand what code is getting executed when or to analyse the flow of control of any application. In this article, we will learn how to get a line number and the filename of the Python script using Python.

Get the Filename and a Line Number in Python

To get the filename and a line number from the executing Python script, we can use the inspect module Python. The inspect module contains several utilities to fetch information about objects, classes, methods, functions, frame objects, and code objects. This library has a getframeinfo() method that retrieves information about a frame or a traceback object. This method accepts a frame argument about which it retrieves details. The currentFrame() method returns the frame object for the caller’s stack frame. We can use these utilities for our use case. Refer to the following Python code to understand the usage.

from inspect import currentframe, getframeinfo

frame = getframeinfo(currentframe())
filename = frame.filename
line = frame.lineno
print("Filename:", filename)
print("Line Number:", line)

Output:

Filename: full/path/to/file/main.py
Line Number: 3

As we can see, the filename attribute will return the full path to the Python file. In my case, the Python file’s name was main.py; hence, it shows main.py in the output. And, the lineno attribute return the line number at which this frame = getframeinfo(currentframe()) statement was executed. The mentioned statement was execute at line 3; hence the output has a 3 after the Line Number label.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python File

  • Get All the Files of a Directory
  • Delete a File and Directory in Python
  • Append Text to a File in Python
  • Check if a File Exists in Python
  • Find Files With a Certain Extension Only in Python
  • Read Specific Lines From a File in Python