user3467226
user3467226

Reputation: 81

How to read a text file that user enters in python

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

Upvotes: 1

Views: 110

Answers (2)

Isaac
Isaac

Reputation: 788

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.

Upvotes: 3

Savir
Savir

Reputation: 18418

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]

Upvotes: 2

Related Questions