How to Read Two Lines from a File at a Time Using Python

How do I read two lines from a file at a time using python

Similar question here. You can't mix iteration and readline so you need to use one or the other.

while True:
line1 = f.readline()
line2 = f.readline()
if not line2: break # EOF
...

Read two lines at a time from a txt file

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)

How to read file N lines at a time?

One solution would be a list comprehension and the slice operator:

with open(filename, 'r') as infile:
lines = [line for line in infile][:N]

After this lines is tuple of lines. However, this would load the complete file into memory. If you don't want this (i.e. if the file could be really large) there is another solution using a generator expression and islice from the itertools package:

from itertools import islice
with open(filename, 'r') as infile:
lines_gen = islice(infile, N)

lines_gen is a generator object, that gives you each line of the file and can be used in a loop like this:

for line in lines_gen:
print line

Both solutions give you up to N lines (or fewer, if the file doesn't have that much).

Read multiple lines in a text file

you can try using lists,

results = []

infile = open('file.txt', 'r').readlines()

for line in infile:
if line.startswith('t'):
index = infile.index(line)

for times in range(0, 3):
results.append(infile[index + times])

print(results)

How to read and write multiple lines of a text file in Python

Thy using a for loop:

with open('file.txt', 'r') as f:
list_of_lines = f.readlines()
t = f"Item {input('some input: ')}\n"
for i in range(len(list_of_lines)):
if i in [1, 2]:
list_of_lines[i] = t

with open("file.txt", "w") as f:
f.writelines(list_of_lines)

file.txt:

Item 1
Item 2
Item 3

Input:

some input: hello

Resulting file.txt:

Item 1
Item hello
Item hello

You can also use a list comprehension with the built-in enumerate method:

t = f"Item {input('some input: ')}\n"
d = [1, 2]

with open('file.txt', 'r') as f:
list_of_lines = [t if i in d else v for i, v in enumerate(f)]

with open("file.txt", "w") as f:
f.writelines(list_of_lines)

Script to read file and print first two and last two lines of it

You're reading the first 4 lines. You need to read through all of them and keep only the last two.

This code reads through all of them, saving the last two lines read:

line1 = f1.readline()
line2 = f1.readline()

last1, last2 = f1.readline(), f1.readline()
while True:
line = f1.readline()
if not line: # eof
break
last1, last2 = line, last1

print("Output:",line1,line2,last2,last1, sep= "")

For example, with a file test.txt:

Line1
line2
Line3
line4
Line5
line6
last line, line 7

You get:

Output:Line1
line2
line6
last line, line 7

How to read 2 lines separately in python

You cannot get a file descriptor (the stuff returned by open) to read only odd or even lines.
It has to read the whole content of the file1.

However and therefore, you do not need to have two file descriptors: you can do the job with only one.
You can iterate over enumerate(file) instead of file.
Instead of giving you the lines, it will give you (index, line) couples.
You can unpack this by doing for id, line in enumerate(file), and then check the remainder of id by 2 to determine if it's odd or even.

file = open(path, 'r')
for id, line in enumerate(file):
if id % 2 == 0:
# The line is even
else:
# The line is odd

1To be fair, you could get a file descriptor to read only odd or even lines, in that you could just skip every other line... But then, why bother to create two descriptors when a single one is already doing the job?



Related Topics



Leave a reply



Submit