0

I am trying to read N lines of file in python.

This is my code

N = 10
counter = 0
lines = []
with open(file) as f:
    if counter < N:    
        lines.append(f:next())
    else:
        break

Assuming the file is a super large text file. Is there anyway to write this better. I understand in production code, its advised not to use break in loops so as to achieve better readability. But i cannot think of a good way not to use break and to achieve the same effect.

I am a new developer and am just trying to improve my code quality.

Any advice is greatly appreciated. Thanks.

aceminer
  • 4,089
  • 9
  • 56
  • 104

2 Answers2

-1

There's no need to break, just iterate N times.

lines = []
afile = open('...')
for i in range(N):
    aline = afile.readln()
    lines.append(aline)
afile.close()
Organis
  • 7,243
  • 2
  • 12
  • 14
-1

There is no loop in your code.

N = 10
counter = 0
lines = []
with open(file) as f:
    for line in f:
        lines.append(line)
        counter += 1
        if counter > N:
            break

(I let you handle the edge case with N = 0 if you need to.)

Or just

import itertools
N = 10
with open(file) as f:
    lines = list(itertools.islice(f, N))
Quentin Roy
  • 7,677
  • 2
  • 32
  • 50