1

While writing some tests, i got stuck on some weird behavior. I finally narrow the problem to file opening. For instance, this one, my.dat:

one line
two lines and no final line break

I then ran that python code:

with open('my.dat') as fd:
    assert fd.read()[-1] == '\n'

With both python 3 and 2, this code does not raise any AssertError.

My question is: why forcing the presence of line jump at the end of files ?

Jignasha Royala
  • 1,032
  • 10
  • 27
aluriak
  • 5,559
  • 2
  • 26
  • 39

1 Answers1

3

It works here. Are you 100% sure that there is not actually a newline at the end of your file? Because many text editors (atom, notepad++) automatically add newlines at the end of a file.

>>> open('a.txt', 'w').write('blabla')
6
>>> open('a.txt', 'r').read()
'blabla'
>>> assert open('a.txt', 'r').read()[-1] == '\n'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
Joost
  • 3,609
  • 2
  • 12
  • 29
  • Scheiße… My vim seems to be contaminated by this behavior. The problem is all about vim now. That's a plot twist. Thanks ! (*[fixed](https://stackoverflow.com/a/16114535/3077939)*) – aluriak Sep 21 '18 at 14:06
  • That is the posix-standard way of writing a file. Vim actually warns you when it opens a file with no newline (it says NOEOL at the bottom), but when it writes the file out, it will add the missing newline. https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline – Aaron Bentley Sep 21 '18 at 14:22
  • As usual, i found an odd behavior, be pissed about it for ten minutes, then SO's community changes my mind. – aluriak Sep 21 '18 at 14:24