Output specific lines by numbers

I want to read lines 25 through 55 from a file, but the range seems to only output one number and 6 lines if it should be 30 lines.

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

print(i)
print(data)

Conclusion:

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

Use the built-in function enumerate:

for i, line in enumerate(hamlettext):
    if i in range(25, 55):
        print(i)
        print(line)
+4
source

You can read the entire file, then slice to get a list of lines:

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

if the file is large, however, it is better to skip 25 lines, then read, then exit the loop so as not to read thousands of other lines:

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())

, , 1 ( 0, 1, enumerate(hamlettext,1), .

+2

So yours iin the above code prints the last line. To read all 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)
-2
source

Source: https://habr.com/ru/post/1684958/


All Articles