Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how to test whether a line is the last one?

Tags:

python

Suppose I want to process each line of a file, but the last line needs special treatment:

with open('my_file.txt') as f:
    for line in f:
        if <line is the last line>:
            handle_last_line(line)
        else:
            handle_line(line)

The question is, how does one implement ? There seems to be no function for detecting end-of-file in Python.

Is there another solution than read the lines into a list (with f.readlines() or similar)?

like image 259
user1387866 Avatar asked Aug 26 '13 17:08

user1387866


People also ask

How do you check if an item is the last in a list Python?

There is 2 indexing in Python that points to the last element in the list. list[ len – 1 ] : This statement returns the last index if the list. list[-1] : Negative indexing starts from the end.

How do you check if a line has a certain string in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

How do you read the first and last line in Python?

Exakt code used for timing: with open(file, "rb") as f: first = f. readline() # Read and store the first line. for last in f: pass # Read all lines, keep final value.


2 Answers

Process the previous line:

with open('my_file.txt') as f:
    line = None
    previous = next(f, None)
    for line in f:
        handle_line(previous)
        previous = line

    if previous is not None:
        handle_last_line(previous)

When the loop terminates, you know that the last line was just read.

A generic version, letting you process the N last lines separately, use a collections.deque() object:

from collections import deque
from itertools import islice

with open('my_file.txt') as f:
    prev = deque(islice(f, n), n)
    for line in f:
        handle_line(prev.popleft())
        prev.append(line)

    for remaining in prev:
        handle_last_line(remaining)
like image 112
Martijn Pieters Avatar answered Oct 31 '22 00:10

Martijn Pieters


You can use itertools.tee to iterate on two copies of an iterable:

next_lines, lines = itertools.tee(file_object)
next(next_lines)
for next_line, line in zip(next_lines, lines):
    handle_line(line)
last_line = next(lines, None)
if last_line is not None:
    handle_last_line(last_line)
like image 33
Bakuriu Avatar answered Oct 30 '22 23:10

Bakuriu