How to get the current open file line in Python?


If a file is open in Python and you want to find the current line number of the open file; we explore different ways, in this article, how you can perform this task using certain modules, functions and methods. Along the way, we discuss some code examples with detailed explanations to elucidate the concepts and strategies involved in the task.

Making Use of the Tell() Method

You can begin by opening the file in read mode by using of the open() function and assigning it to a variable ‘file’. Then using the read() method you load the contents of the file as a string in another variable ‘contents’.

To get the current line number, you go on to count the number of newline characters ("\n") in this string using the count() method. And you have to add 1 to account for starting from line 1. Finally, the file is closed with close() function and the line number is printed out to the console to confirm its veracity. Here’s an implementation:

Assuming there is a file myfile.txt as follows.

#myfile.txt
This is line number one.
This is line number two.
This is line number three.
This is line number four.

Example

#The file is opened in read mode
file = open("example.txt", "r")

#The contents of the file are read
contents = file.read()

# The current line number is fetched
line_number = contents.count("\n") + 1

# The file is closed
file.close()

# The current line number is printed
print("Current line number:", line_number)

Output

If the above code is run, we get the following.

Current line number: five

Making Use of Enumerate() Function

Alternatively, you may use Pythons' built-in enumerate() function. The lines of the file are iterated over by the enumerate() method. It gives as output a tuple containing the line count and the line content each time.

In this example, we don't need to perform any operation inside the loop. We only need to iterate through all the lines so as to reach the last line and its count or number.

After navigating through the loop, the file is closed using the close() function and the line number of the current line is printed to the console.

Assuming there is a file myfile.txt as follows.

#myfile.txt
This is line number one.
This is line number two.
This is line number three.
This is line number four.

Example

# The file is opened in read mode
file = open("myfile.txt", "r")

# Iteration is done over the lines and the current line number is fetched
for line_number, line in enumerate(file, start=1):
   pass

# The file is closed
file.close()

# The current line number is printed
print("Current line number:", line_number)

Output

If the above code is run, we get the following.

Current line number: 5

Utilizing the Linecache Module

Example

This code imports the linecache module, which facilitates reading lines from a file.

This code opens the file, counts the total number of lines in it, and then uses the total_lines as the line number to fetch the last line in the file. The count of newline characters is added by 1 to get the current line number.

Assuming there is a file myfile.txt as follows.

#myfile.txt
This is line number one.
This is line number two.
This is line number three.
This is line number four.

Example

import linecache

file_path = "myfile.txt"
import linecache

file_path = "myfile.txt"

# Get the total number of lines in the file
total_lines = len(open(file_path).readlines())

# The current line number is fetched
line_number = total_lines

# The current line number is printed
print("Current line number:", line_number)

Output

If the above code is run, we get the following.

Current line number: 5

Utilizing the Readline() Method

Example

  • The code opens the file "myfile.txt" in read mode when the open() function is used and assigns it to the variable ‘file’.

  • Inside the while loop, the readline() method is used to read every line of the file one by one till the end of the file is reached.

  • The line_number is increased by 1 on each iteration.

  • After the loop terminates, the file is closed using the close() method, and the current line number is printed to the console.

Assuming there is a file myfile.txt as follows.

#myfile.txt
This is line number one.
This is line number two.
This is line number three.
This is line number four.

Example

# The file is opened in read mode
file = open("myfile.txt", "r")

# The file is read line by line till the end
line_number = 0
while file.readline():
   line_number += 1

# The file is closed
file.close()

# The current line number is printed
print("Current line number:", line_number)

Output

If the above code is run, we get the following.

Current line number: 5

Utilizing the Seek() Method

Example

  • The file "myfile.txt" is opened in read mode and assigned to the variable ‘file’.

  • The file position is moved to the end of the file by the seek() method. The 0 parameter shows the offset from the current position, and 2 indicates the reference point at the end of the file.

  • The tell() method is used to fetch the current byte offset or file position within the file and assign it to the byte_offset variable.

  • The read() method is used to read the file contents which are then stored inside the contents variable.

  • The newline characters ("\n") in the file contents are counted by using the count() method, and 1 is added to account for the closing line.

  • Finally, the file is closed using the close() method, and the current line number is printed to the console.

Assuming there is a file myfile.txt as follows.

#myfile.txt
This is line number one.
This is line number two.
This is line number three.
This is line number four.

Example

with open("myfile.txt", "r") as file:
    # The end of the file is reached
    file.seek(0, 2)

    # The file position or current byte offset is fetched
    byte_offset = file.tell()

    # Move the file pointer to the beginning
    file.seek(0)

    # Read the file contents
    contents = file.read()

    # The number of newline characters is counted
    line_number = contents.count("\n") + 1

# The current line number is printed
print("Current line number:", line_number)

Output

If above code is run, we get the following.

Current line number: 5

In short, we have seen various code examples to get the current line number of an open file in Python. Additional examples showcase various different methods to achieve the same process of fetching the current line number of an open file in Python. You can always choose the method that best meets your requirements and use it to fetch the current line number of an open file on your system.

Updated on: 20-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements