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.

0

2 Answers 2

-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() 
Sign up to request clarification or add additional context in comments.

Comments

-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)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.