擅长:python、mysql、java
<p>Python 3允许您定义特定文件的换行符。很少使用它,因为默认的<em>通用换行</em>模式非常宽容:</p>
<blockquote>
<p>When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.</p>
</blockquote>
<p>因此,这里应该明确指出只有'\r\n'是行尾:</p>
<pre><code>f= open("f.txt",mode='r',encoding='utf8', newline='\r\n')
# use enumerate to show that second line is read as a whole
for i, line in enumerate(fd):
print(i, line)
</code></pre>