Print line number in python

Python print with line number and variable name

While the program is small, there are no problems with this. Let’s assume that you have started working with some class with ~ 3000 lines (legacy code) and you need to quickly look at any values. The number of «prints» increases, and it becomes not easy to understand from the first time which «print» refers to which variable. You can of course write like this.

Yes, that’s better. But I would still like to see both the line number and the type of variable. And in some cases, the path to the file. For such cases, I have written a small (and very useful) utility that will make your life easier. Let’s try to install it.

from simple_print, import sprint master = "yoda" # Print the variable name with the line number sprint(master) # Add blue paint sprint(master, c="blue") # Add a white background sprint(master, c="blue", b="on_white") # Add underline sprint(master, c="blue", b="on_white", a="underline") # ADD the path to sprint(master, c="blue", b="on_white", a="underline", p=True) # Return as a string s = sprint(master, s=True) 

Image description

And of course you can use indents for debugging in forloops:

def test_indent(): fruits = ["lemon", "orange", "banana"] sprint(fruits, c="green") for fruit in fruits: sprint(fruit, c="yellow", i=4) 

Image description

The source code can be viewed here https://github.com/Sobolev5/simple-print Productive development for you. Thanks for reading.

Читайте также:  Php ini upload files

Источник

How to print line numbers of a file in Python?

EasyTweaks.com

Use the Python enumerate function to loop through a text or csv file and then, for each line print the line number and the line values. Here’s a simple snippet:

with open (your_file_path, 'r') as f: for i, line in enumerate (f): print(f'Line number:; Content: '.strip()) 

Create an Example file

Assuming that you have the following multi-line text written into a text file in your operating system (either Windows, Linux or macOS)

This is our log file.
It is located at the C:\MyWork directory.
This file was built with Python.

Find the line numbers and print the line contents

Our task is to print for each line of the file the line number and the line contents.

# import the path library - ships from Python 3.4 and onwards from pathlib import Path # replace with path of file in your environment file_path = Path('C:\WorkDir\multi_line_file.txt') # Verify that file exists if file_path.is_file(): #Open file and loop through lines, print line number and content with open (file_path, 'r') as f: for i, line in enumerate (f): print(f'Line number:; Content: '.strip()) else: print("The file doesn't exist.")

This will return the following result:

Line number:1; Content: This is our log file. Line number:2; Content: It is located at the C:\MyWork directory. Line number:3; Content: This file was built with Python.

Next we would like to search for a specific string in the file contents and print only the specific line which contains the string. We will use the re (regular expressions) module to easily parse the file.

 with open (file_path, 'r') as f: for i, line in enumerate (f): # search for words ending with the string 'thon' if (re.search(r'thon\b', line)): print(f'Line number:; Content: '.strip()) 

This will render the following result:

Line number:3; Content: This file was built with Python.

Get number of lines in a Python file

To count the number of lines in a text file with Python, proceed as following:

file_path = Path('C:\WorkDir\multi_line_file.txt') with open (file_path, 'r') as f: for l in file: l += 1 print (f'The file line count is : ') 

Источник

How to add line numbers and filename when printing in Python

We all do it. Yes we all use print for debugging.
Should we do it? Maybe.
Should we feel guilty about it? No!

In fact, printing to the console is a perfectly valid way of debugging. Source: Tips for debugging with print()

But one of the of problems with printing to the console, is that in large scripts you can end up with hundreds of print statements and often no guidance from where any particular print statements is being called.

So it would be great if we could print the file and line number of where the print statement lives.

In the past this has been a complete nightmare. Often you end up calling modules you’ve never heard of from some script found on some dodgy looking site and it all just feel unpythonic and icky.

Wouldn’t it be great if someone had already handled the icky for you?

Enter the Rich formatting library!

The Rich library is built to for writing rich text. You know text with colors and other things like … line numbers!

Lets get started!

In the virtual environment of your choice – begin by installing Rich.

Now that we have Rich installed. Let’s create a script called printlog.py

And begin by setting up Rich and the Rich Console. The Console is a function that allows you to readily create richly formatted text.

from rich.console import Console console = Console()

And now we are ready to rock. To print something to the console you call console.log(«Your text») and the text will be printed along with the file name and line number that the console.log() statement lives on.

Let’s populate printlog.py with some code.

from rich.console import Console console = Console() console.log("Starting loop.", style="red") for i in range(100): # Do something pass console.log(f"In between loops ", style="bright_yellow") for j in range(200): # Do something else pass console.log(f"Finished! ", style="green")

In line 1 and 3 we are setting up rich. In line 5 we are printing to the console that we are beginning – and we’ve given it the color red . You remember how I said rich allows you to print colors? Well here we are! There are plenty of colours to choose from – as well as all the hex and rgb colors as well (provided your terminal supports them).

Then we run a loop – in practice this would be your code. We print out where we are up to with another console.log() command, run another loop and then print some more.

You should get output much like this:

Notice that not only do we get the filename and line number on the right – but we also get the time (to the second) that the script ran on the left.

All that info for free! And in a really pythonic way.

Wow – what a great library!

Plus console.log() can be used in any python script that prints to the console. I use it in my Django projects all the time.

So check out the Rich console.log() command today!

Leave a Reply Cancel reply

You must be logged in to post a comment.

Источник

Get the Filename and a Line Number in Python

Get the Filename and a Line Number in Python

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) 
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 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.

Related Article — Python File

Источник

Оцените статью