3

So let's say I have a text file, which contains this:

a
b
c
d
e

I want to iterate through every line of this file, but in the process also get the line following the first line. I have tried this:

with open(txt_file, "r") as f:
    for line1, line2 in itertools.zip_longest(*[f] * 2):
        if line2 != None:
            print(line1.rstrip() + line2.rstrip())
        else:
            print(line1.rstrip())

which returns something like:

ab
cd
e

However, I would like to have output like this:

ab
bc
cd
de
e

Anyone have an idea for how to accomplish this? Thanks in advance!

hongdekong
  • 41
  • 2

4 Answers4

6

Why iterator? Simply cache one line:

with open("t.txt","w") as f:
    f.write("a\nb\nc\nd\ne")

with open("t.txt", "r") as f:
    ll = next(f) # get the first line
    for line in f: # get the remaining ones
        print(ll.rstrip() + line.rstrip())
        ll = line # cache current line as last line
    print(ll) # get last one

Output:

ab
bc
cd
de
e 
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
2
with open(txt_file, "r") as f:
   last = None
   for line in f:
      if not last is None:
         print(last + line.rstrip())
      last = line.rstrip()
   # print the last line
   print line.rstrip()
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
0

A simple solution would be:

with open(txt_file, "r") as f:
    content = f.read().splitlines()
    for i, line in enumerate(content):
        if i == len(content) - 1:
            print(line)
        else:
            print(line + content[i+1])
Mark
  • 214
  • 2
  • 13
0

You can also create a generator which takes an iterable as an input parameter and yields tuples of (previous_element, element).

def with_previous(iterable):
    iterator = iter(iterable)
    previous_element = next(iterator)
    for element in iterator:
        yield previous_element, element
        previous_element = element

You need to handle the special cases if the iterable contains only one or two elements.

Dennis
  • 71
  • 5