Outputting specific lines by number

73 views Asked by At

I want to read lines 25 to 55 from a file, but the range seems to be only outputting a single number and 6 lines, when it should be 30 lines.

hamlettext = open('hamlet.txt', 'r')
for i in range (25,55):
    data = hamlettext.readlines(i)

print(i)
print(data)

Output:

54
['\n', 'Mar.\n', 'O, farewell, honest soldier;\n', "Who hath reliev'd you?\n"]
3

There are 3 answers

3
Zach Gates On BEST ANSWER

Use the builtin enumerate function:

for i, line in enumerate(hamlettext):
    if i in range(25, 55):
        print(i)
        print(line)
1
Venkata S S K M Chaitanya On

So your i in the code above is printing the last line. To read all the lines from 25 to 55 you need to print the data inside the loop.

    hamlettext = open('hamlet.txt', 'r')
    for i in range (25,55):
        data = hamlettext.readlines(i)

        print(i)
        print(data)
0
Jean-François Fabre On

You could read the file fully then slice to get the list of lines:

with open('hamlet.txt', 'r') as f:
    data = f.readlines()[25:55]

if the file is big, though, it's better to skip 25 lines, then read, then get out of the loop to avoid reading the thousand other lines for nothing:

with open('hamlet.txt', 'r') as f:
    for i, line in enumerate(hamlettext):
        if i < 25:
           continue
        elif i >= 55:
           break
        else:
           print(i,line.rstrip())

also note that if you're comparing the line numbers with a text editor, there's a 1 offset (python starts at 0, editors start at 1, so you can use enumerate(hamlettext,1) to fix that properly.