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.

1

3 Answers 3

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

2 Comments

Can you please say why it is best practice to use with?
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())

2 Comments

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: you need to strip() it to remove the newline. I've adapted the answer
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])

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.