-1

I am trying to read a file, get how many lines it has, and check new lines to see if it met a specific condition.

with open(path, "r") as g:
     readlen = len(g.readlines())
while True:
     with open(path, "r") as h:
          latest_line = fix_line(h.readlines()[readlen])

I am so confused because it worked in another section of code. (Identical to above)

  • 2
    Lists are _zero-indexed_, meaning if `readlen == 1` the lowest index is `0` – Emanuel P Mar 05 '23 at 12:31
  • It's hard to say exactly what might be causing the issue without more information, but one thing you could try is to make sure that the file you're trying to read is in the correct directory and that you have the correct file path specified in your code. Another thing to consider is whether the "fix_line" function is working correctly and whether it's returning the values that you're expecting. You may want to try printing out the values of "readlen" and "latest_line" to see if they're what you expect them to be. – Lord volkath Mar 05 '23 at 12:34

1 Answers1

1

There are several issues with your code.

First of all, lists are indeed 0-indexed, so you need to substract one (because you start counting from 0, the highest index in the list is the length minus one)

So, this does print the last line:

with open("./hello.txt") as f:
    length = len(f.readlines())

with open("./hello.txt") as g:
    last_line = g.readlines()[length-1]

print(last_line)

However, in python, there is an easier way to get the last element of a list. You can use negative indexes to wrap around, so, this works as well:

with open("./hello.txt") as g:
   last_line = g.readlines()[-1]

print(last_line)

However, if you plan to do more than just read the last line, I would suggest simply storing the list of strings into a variable.

with open("./hello.txt") as g:
    file = g.readlines()

# Using your original method
last_line1 = file[len(file)-1]

# Using the negative indexes
last_line2 = file[-1]

print(last_line1, last_line2)

If your file is big and you cannot just read the entire file, and you need to read only the last line, it can also be beneficial to check out this question: How to read the last line of a file in Python?

I hope that helps!

Egeau
  • 459
  • 1
  • 9
  • `readlines()` returns a `list`. The actual file object is an iterator, not what `.readlines()` returns. Doing `list(g.readlines())` is redundant and wasteful; you want *either* `list(g)` *or* `g.readlines()`, not both. – ShadowRanger Mar 05 '23 at 13:07
  • You're right. I'm stupid. :P I've edited my post. I think I got confused by the fact that the question calls it twice, suggesting to me that it was one of those file functions that returns another iterator. ;P – Egeau Mar 05 '23 at 13:10