How to print line numbers of a file in Python?

Get and print line numbers in a file

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:{i+1}; Content: {line}'.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:{i+1}; Content: {line}'.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.

Print specific lines from a file

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:{i+1}; Content: {line}'.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 : {l}')

Recommended learning

How can i write a Python list into a text file on my computer?