Get line number in file python

How to Find Line Number of a Given Word in text file using Python?

In this article, we will show you how to get a line number in which the given word is present from a text file using python.

Assume we have taken a text file with the name TextFile.txt consisting of some random text. We will return the line numbers in which the given word is present from a text file

Good Morning TutorialsPoint This is TutorialsPoint sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome TutorialsPoint Learn with a joy

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the path of the text file.
  • Create a variable (which holds the line number) and initialize its value to 1.
  • Enter the word as static/dynamic input and store it in a variable.
  • Use the open() function(opens a file and returns a file object as a result) to open the text file in read-only mode by passing the file name, and mode as arguments to it (Here “r” represents read-only mode).
with open(inputFile, 'r') as fileData:
  • Traverse in each line of the text file using the for loop.
  • Use the split() function(splits a string into a list. We can define the separator; the default separator is any whitespace) to split each line of a text file into a list of words and store it in a variable.
  • Using the if conditional statement and “in” keyword, check whether the given word is present in the above words list. The in keyword works in two ways −
The in keyword is used to determine whether a value exists in a sequence (list, range, string etc).

It is also used to iterate through a sequence in a for loop

Читайте также:  Python site packages utf 8

Example

The following program to delete a given line from a text file and print the result file content after deleting that line −

# input text file inputFile = "ExampleTextFile.txt" # storing the current line number lineNumber = 1 # Enter the word givenWord = "TutorialsPoint" print('The word is present in the following lines:') # Opening the given file in read-only mode. with open(inputFile, 'r') as fileData: # Traverse in each line of the file for textline in fileData: # Splitting the line into list of words wordsList = textline.split() # Checking if the given word is present in the above words list if givenWord in wordsList: # Print the line number, if the given word is found print(lineNumber) # Increase the value of linenumber by 1 lineNumber += 1 # Closing the input file fileData.close()

Output

On executing, the above program will generate the following output −

The word < TutorialsPoint >is present in the following lines: 1 2 6

We read a text file containing some random text in this program. We created a variable to store the current line number and initialized it to 1, the starting line number. We proceeded through the text file line by line, breaking each line down into a list of words and checking to see if the given word was in the list. If it is present, it prints the current line Number. For every line, the value of the line number is increased by one.

Источник

Python Count Number of Lines in a File

If the file is significantly large (in GB), and you don’t want to read the whole file to get the line count, This article lets you know how to get the count of lines present in a file in Python.

Table of contents

Steps to Get Line Count in a File

Count Number of Lines in a text File in Python

  1. Open file in Read Mode To open a file pass file path and access mode r to the open() function.
    For example, fp= open(r’File_Path’, ‘r’) to read a file.
  2. Use for loop with enumerate() function to get a line and its number. The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the open() function to the enumerate() . The enumerate() function adds a counter to each line.
    We can use this enumerate object with a loop to access the line number. Return counter when the line ends.
  3. Close file after completing the read operation We need to make sure that the file will be closed properly after completing the file operation. Use fp.close() to close a file.

Consider a file “read_demo.txt.” See an image to view the file’s content for reference.

text file

# open file in read mode with open(r"E:\demos\files\read_demo.txt", 'r') as fp: for count, line in enumerate(fp): pass print('Total Lines', count + 1)
  • The enumerate() function adds a counter to each line.
  • Using enumerate, we are not using unnecessary memory. It is helpful if the file size is large.
  • Note: enumerate(file_pointer) doesn’t load the entire file in memory, so this is an efficient fasted way to count lines in a file.

Generator and Raw Interface to get Line Count

A fast and compact solution to getting line count could be a generator expression. If the file contains a vast number of lines (like file size in GB), you should use the generator for speed.

This solution accepts file pointer and line count. To get a faster solution, use the unbuffered (raw) interface, using byte arrays, and making your own buffering.

def _count_generator(reader): b = reader(1024 * 1024) while b: yield b b = reader(1024 * 1024) with open(r'E:\demos\files\read_demo.txt', 'rb') as fp: c_generator = _count_generator(fp.raw.read) # count each \n count = sum(buffer.count(b'\n') for buffer in c_generator) print('Total lines:', count + 1)

Use readlines() to get Line Count

If your file size is small and you are not concerned with performance, then the readlines() method is best suited.

This is the most straightforward way to count the number of lines in a text file in Python.

  • The readlines() method reads all lines from a file and stores it in a list.
  • Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

Open a file and use the readlines() method on file pointer to read all lines.

with open(r"E:\demos\files\read_demo.txt", 'r') as fp: x = len(fp.readlines()) print('Total lines:', x) # 8

Note: This isn’t memory-efficient because it loads the entire file in memory. It is the most significant disadvantage if you are working with large files whose size is in GB.

Use Loop and Sum Function to Count Lines

You can use the for loop to read each line and pass for loop to sum function to get the total iteration count which is nothing but a line count.

with open(r"E:\demos\files\read_demo.txt", 'r') as fp: num_lines = sum(1 for line in fp) print('Total lines:', num_lines) # 8

If you want to exclude the empty lines count use the below example.

with open(r"E:\demos\files\read_demo.txt", 'r') as fp: num_lines = sum(1 for line in fp if line.rstrip()) print('Total lines:', num_lines) # 8

The in Operator and Loop to get Line Count

Using in operator and loop, we can get a line count of nonempty lines in the file.

  • Set counter to zero
  • Use a for-loop to read each line of a file, and if the line is nonempty, increase line count by 1
# open file in read mode with open(r"E:\demos\files_demos\read_demo.txt", 'r') as fp: count = 0 for line in fp: if line != "\n": count += 1 print('Total Lines', count)

Count number of lines in a file Excluding Blank Lines

For example, below is the text file which uses the blank lines used to separate blocks.

Jessa = 70 Kelly = 80 Roy = 90 Emma = 25 Nat = 80 Sam = 75

When we use all the above approaches, they also count the blank lines. In this example, we will see how to count the number of lines in a file, excluding blank lines

count = 0 with open('read_demo.txt') as fp: for line in fp: if line.strip(): count += 1 print('number of non-blank lines', count)
number of non-blank lines 6

Conclusion

  • Use readlines() or A loop solution if the file size is small.
  • Use Generator and Raw interface to get line count if you are working with large files.
  • Use a loop and enumerate() for large files because we don’t need to load the entire file in memory.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

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 : ') 

Источник

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