简体   繁体   English

Python在打开的文件末尾添加了新行

[英]Python adds a new line at the end of opened file

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 : 例如,这个my.dat

one line
two lines and no final line break

I then ran that python code: 然后,我运行了该python代码:

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

With both python 3 and 2, this code does not raise any AssertError. 使用python 3和2时,此代码不会引发任何AssertError。

My question is: why forcing the presence of line jump at the end of files ? 我的问题是:为什么强制在文件末尾存在行跳转?

It works here. 它在这里工作。 Are you 100% sure that there is not actually a newline at the end of your file? 您是否100%确定文件末尾实际上没有换行符? Because many text editors (atom, notepad++) automatically add newlines at the end of a file. 因为许多文本编辑器(atom,notepad ++)会在文件末尾自动添加换行符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM