-2

I need to read the first 30 lines of a file.

with open(filename) as f:
    lines = f.readlines(30)
print len(lines)

300

am I missing something?

Bob
  • 10,741
  • 27
  • 89
  • 143
  • possible duplicate of [Read first N lines of a file in python](http://stackoverflow.com/questions/1767513/read-first-n-lines-of-a-file-in-python) – Chaker Jul 19 '15 at 00:12
  • I looked into that. I don't know why the code above is not working – Bob Jul 19 '15 at 00:13
  • How about for a starter check out documentation on what is readlines parameter actually is https://docs.python.org/2/library/stdtypes.html?highlight=readlines#file.readlines – Andrey Jul 19 '15 at 00:14
  • it reads all the lines, see what argument means: https://docs.python.org/2/library/stdtypes.html?highlight=readlines#file.readlines – m.wasowski Jul 19 '15 at 00:14

2 Answers2

3

According to https://docs.python.org/2/library/stdtypes.html#file.readlines, the 30 is not the number of lines to read. It is a buffer hint given in bytes.

melpomene
  • 84,125
  • 8
  • 85
  • 148
1

After reading the comments i have decided to give "answer" to the question: how to read first 30 lines from a file. Answer is: readline()

lines = []
for i in range(30):
    lines.append(f.readline())

Done.

Laszlowaty
  • 1,295
  • 2
  • 11
  • 19