0

Using Python version 3

I am using the code:

f = open("cinema.txt","r")
print(f.read()) 

This then goes on to open the cinema text file. This text file contains 50 lines containing 50 movie titles.

What I want to do is to be able to read for example line 5. I also want to be able to read for example lines 15-20. Can someone please advise what is the extra bit I need to add into the code. I have searched around on the Internet but I can't find an answer that work.

Biffen
  • 6,249
  • 6
  • 28
  • 36
Ellen
  • 9
  • 1
  • 1
  • 1

3 Answers3

4

Use with open(), don't use open(), it's best practice.

data = []
with open("cinema.txt","r") as f:
    data = f.readlines() # readlines() returns a list of items, each item is a line in your file

print(data[5]) # print line 5

for i in range(14, 19):
    print(data[i])
Huy Vo
  • 2,418
  • 6
  • 22
  • 43
3

You could try to use enumerate and then check for the line number: Note that i starts at i so i == 4 matches the 5th line.

with open('cinema.txt') as f:
    for i, line in enumerate(f):
        if i == 4:
            print(line.strip())
        if 14 < i < 19:
            print(line.strip())
hansaplast
  • 11,007
  • 2
  • 61
  • 75
  • Thanks so much hansaplast - that has saved a lot of time, could you tell me what extra bit do I need to add? I want it to be single line spaced when it outputs to file. – Ellen Feb 04 '17 at 12:11
  • @ellen: you need to `strip()` it to remove the newline. I've adapted the answer – hansaplast Feb 04 '17 at 12:12
1

You can record line in the list and display the list slice.

f = open("cinema.txt")
lines = f.readlines()
a = 15
b = 20
print("\n".join(lines[a:b + 1]))

or

for i in range(a, b + 1):
    print('line №' + str(i) + ': ' + lines[i])