How to get the current open file line in Python?

When working with files in Python, you may need to determine the current line number while reading or processing the file. This article explores different methods to get the current line number of an open file using various Python functions and modules.

Method 1: Using count() to Count Newlines

The simplest approach is to read the entire file content and count the newline characters ("\n"). Each newline represents the end of a line, so adding 1 gives us the total number of lines.

First, let's create a sample file to work with ?

# Create a sample file
with open("sample.txt", "w") as f:
    f.write("This is line number one.\n")
    f.write("This is line number two.\n")
    f.write("This is line number three.\n")
    f.write("This is line number four.")

print("Sample file created successfully")
Sample file created successfully

Now let's get the current line number by counting newlines ?

# Open the file and count lines
with open("sample.txt", "r") as file:
    contents = file.read()
    line_number = contents.count("\n") + 1

print("Current line number:", line_number)
Current line number: 4

Method 2: Using enumerate() Function

The enumerate() function provides both the line number and content as you iterate through the file. This method is memory-efficient as it doesn't load the entire file at once.

# Use enumerate to get line numbers
with open("sample.txt", "r") as file:
    for line_number, line_content in enumerate(file, start=1):
        pass  # Just iterate to count lines

print("Current line number:", line_number)
Current line number: 4

Method 3: Using readline() Method

The readline() method reads one line at a time. By counting how many times we can call it before reaching the end of file, we get the total line count.

# Count lines using readline()
with open("sample.txt", "r") as file:
    line_number = 0
    while file.readline():
        line_number += 1

print("Current line number:", line_number)
Current line number: 4

Method 4: Using readlines() Method

The readlines() method returns a list of all lines in the file. The length of this list gives us the total number of lines directly.

# Count lines using readlines()
with open("sample.txt", "r") as file:
    lines = file.readlines()
    line_number = len(lines)

print("Current line number:", line_number)
Current line number: 4

Tracking Current Position During File Processing

If you need to track the current line number while actively processing a file, you can maintain a counter during iteration ?

# Track line number during processing
current_line = 0
with open("sample.txt", "r") as file:
    for line in file:
        current_line += 1
        print(f"Processing line {current_line}: {line.strip()}")

print(f"Total lines processed: {current_line}")
Processing line 1: This is line number one.
Processing line 2: This is line number two.
Processing line 3: This is line number three.
Processing line 4: This is line number four.
Total lines processed: 4

Comparison of Methods

Method Memory Usage Best For
count("\n") High (loads entire file) Small files, simple counting
enumerate() Low (line by line) Processing with line numbers
readline() Low (line by line) Manual line processing
readlines() High (loads all lines) When you need all lines as list

Conclusion

Use enumerate() for memory-efficient line counting during file processing. For simple counting, readlines() provides the most direct approach. Choose count("\n") for small files where you only need the total count.

Updated on: 2026-03-24T17:21:52+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements