4

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"]
Zach Gates
  • 4,045
  • 1
  • 27
  • 51
aiwan
  • 107
  • 7

3 Answers3

4

Use the builtin enumerate function:

for i, line in enumerate(hamlettext):
    if i in range(25, 55):
        print(i)
        print(line)
Zach Gates
  • 4,045
  • 1
  • 27
  • 51
  • thank you! both answers work just fine - the enumerate was able to print it a bit cleaner, without the quotes in each line. Is this simply an inbuilt cleanup within enumerate? – aiwan Sep 02 '17 at 19:42
  • @aiwan: According to the documentation, `enumerate` returns a tuple containing a count (from start, which defaults to 0) and the values obtained from iterating. In the case of a file, it creates pairs like `(0, 'this is the first line\n')` which can then be used to keep track of a lines position. You can read more about `enumerate` by clicking the hyperlink in my answer. – Zach Gates Sep 02 '17 at 19:45
  • @aiwan: Sure thing. I see that you're new to Stack Overflow (welcome!), and, if an answer helped you, you can choose to upvote it or "accept" it as the correct answer. – Zach Gates Sep 02 '17 at 19:52
2

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
-2

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)
  • This is incorrect, as `readlines(i)` does not retrieve line `i` from the file. "If given an optional parameter `sizehint`, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that." – Zach Gates Sep 02 '17 at 19:37