1

All i have gotten this far is this.

f = open(input('enter file'))
lines = f.readlines()
lines[10]
print("lines")

any help? i changed it to lines[0,11]

QUESTION HAS BEEN ANSWERED

user3467226
  • 81
  • 1
  • 2
  • 8

2 Answers2

3

BorrajaX's solution is not ideal because it reads the whole file. Better is to use python's built in file iterator. enumerate wraps this iterator to count the number of lines returned.

f = open(input('enter file'))
for lnum, line in enumerate(f):
  print(line, end='')
  if lnum == 9:
    break

Edit Another method (credit to Robᵩ):

import itertools
f = open(input('enter file'))
print(''.join(itertools.islice(f, 10)))

This is slightly faster, but has higher peak memory.

Isaac
  • 758
  • 5
  • 16
  • 1
    Agree, but I didn't want to deviate too much from the original question (but yeah, that's definitely better memory-wise) – Savir Apr 07 '14 at 16:56
  • 1
    If we are going to stop iterating after 10, try `for line in itertools.islice(f, 10): print(line,end='')` or even `print(''.join(itertools.isclice(f, 10),end='')`. – Robᵩ Apr 07 '14 at 17:13
  • Ya was trying to keep it simple. `sys.stdout.write()` is a little more efficient than the print, too. I like your oneliner though. – Isaac Apr 07 '14 at 17:15
2

lines is a list. lines[10] gives you the 11th element of the lines list. It doesn't slice it (check this answer about slicing notation).

Also, with print("lines") you're printing the string "lines" , not the variable lines. Try:

f = open(input('enter file'))
lines = f.readlines()
print(lines[0:10])

EDIT:

Thanks to user Robᵩ to help me realize that I've forgotten my basic Python. :-D

You don't need a min to control the slicing if you have less than 10 elements:

>>> [1,2,3,4,5][0:10]
[1, 2, 3, 4, 5]
Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
  • 1
    The bit about `min` is wholly unnecessary. Slicing works correctly, even if there are too few elements in lines. – Robᵩ Apr 07 '14 at 16:50