Search code examples
pythonpython-3.xpython-itertoolsreadlinereadlines

Read two lines at a time from a txt file


The 1st piece of code shown below reads one line from a txt file

It reads one line at a time but what I'd like to achive is making it read two lines at once.

I tried to call the function twice, but all what it does is it reads the same line and print it twice.

I tried using the itertools and islice function but it doesn't seem to be working, I'm missing something.

Sorry, it's the result of 8 days experience with Python 🤭.

How can I make it read N lines at once?

file = open('textfile.txt', 'r')
filelines = file.readlines()
file.close()

for line in filelines:
    if line != '\n':
        api.update_status(line)
...

An attempt to resolve the problem using islice().

from itertools import islice

with open('file.txt') as file:

  while True:

    next_n_lines = islice(file, 2)

    if not next_n_lines:

        break

Solution

  • you can iterate over the file using enumerate to get line numbers, and simply store even number lines in a temp variable, and move on to the next odd number line. On odd number lines you can then have access to the previous line as well as the current line.

    with open('somefile.txt', 'r') as f:
        lastline = ''
        for line_no, line in enumerate(f):
            if line_no % 2 == 0: #even number lines (0, 2, 4 ...) go to `lastline`
                lastline = line
                continue #jump back to the loop for the next line
            print("here's two lines for ya")
            print(lastline)
            print(line)