0

I pull some data from DB and save it to a text file called "databaseoutput.txt". When I run the code below all lines are displayed except the last one - and I know it's there because when I open the file the line that's missing when I run the code below is present

with open("databaseoutput.txt", 'r', encoding='utf-8') as f:
    for line in f:
        print(line)

What can be causing this?

Seb_
  • 35
  • 7
  • Possible duplicate of [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Pedro Lobito Apr 03 '19 at 15:10
  • I don't see anything wrong with that code. Does the file contain formatting characters (such as linefeeds) that could alter the on-screen appearance of the output? – John Gordon Apr 03 '19 at 15:10
  • 1
    I tried the code myself and everything is working fine. Can you provide your databaseoutput.txt ? – epsilonmajorquezero Apr 03 '19 at 15:11
  • @epsilonmajorquezero unfortunately I can't as this company's data but what I can say is the last 3 lines will be something like: *userA *userB *userC So I would assume they're similar and if the line second and third from the and are read then the last would be read too – Seb_ Apr 03 '19 at 15:12
  • I deleted my wrong answer. Seems like a problem with the encoding. – echefede Apr 03 '19 at 15:14
  • This shouldn't cause any issue, and actually tried and nothing is wrong with that char. – epsilonmajorquezero Apr 03 '19 at 15:14
  • @Seb_ Try reading without the encoding (Either with 'r' or 'rb') and see if the last line appears there. – epsilonmajorquezero Apr 03 '19 at 15:16
  • @echefede I've removed the encoding and still the same – Seb_ Apr 03 '19 at 15:17
  • Without a [mcve] there's nothing more we can do, except state the obvious; this code *should* work (even if the file lacks a final newline, for example). – tripleee Apr 03 '19 at 15:17
  • @Seb_ look for the actual file encoding – echefede Apr 03 '19 at 15:20
  • If you change the print statement to some fixed message, like `print("hello")`, does it print the correct amount of times? – John Gordon Apr 03 '19 at 15:21
  • Demo, no repro: https://ideone.com/7e3guG – tripleee Apr 03 '19 at 15:23

1 Answers1

1

I just had the same problem as you. When creating my text file I forgot to close it with:

f.close()
celw10
  • 11
  • 2