<p>我有一些文件有时带有奇怪的行尾字符,比如<code>\r\r\n</code>。有了这个,它就像我想要的那样工作:</p>
<pre><code>with open('test.txt', 'wb') as f: # simulate a file with weird end-of-lines
f.write(b'abc\r\r\ndef')
with open('test.txt', 'rb') as f:
for l in f:
print(l)
# b'abc\r\r\n'
# b'def'
</code></pre>
<p>我希望能够从字符串</em>获得相同的结果<em>。我考虑过<code>splitlines</code>,但结果不一样:</p>
<pre><code>print(b'abc\r\r\ndef'.splitlines())
# [b'abc', b'', b'def']
</code></pre>
<p>即使使用<code>keepends=True</code>,结果也不一样</p>
<p><strong>问题:如何与<code>for l in f</code>和<code>splitlines()</code>具有相同的行为?</strong></p>
<p>链接:<a href="https://discuss.python.org/t/changing-str-splitlines-to-match-file-readlines/174" rel="nofollow noreferrer">Changing str.splitlines to match file readlines</a>和<a href="https://bugs.python.org/issue22232" rel="nofollow noreferrer">https://bugs.python.org/issue22232</a></p>
<p>注意:我不想把所有的东西都放在一个<code>BytesIO</code>或<code>StringIO</code>中,因为它有x0.5的速度性能(已经过基准测试);我想保留一个简单的字符串。所以它不是<a href="https://stackoverflow.com/questions/141449/how-do-i-wrap-a-string-in-a-file-in-python">How do I wrap a string in a file in Python?</a>的复制品</p>