...但这不能处理完全混乱的约定的“混合”文本文件(是的,它们仍然存在!)
实际上它应该可以正常工作:
>>> s = 'hello world\nline 1\r\nline 2'
>>> s.splitlines()
['hello world', 'line 1', 'line 2']
>>> '\n'.join(s.splitlines())
'hello world\nline 1\nline 2'
你使用的是什么版本的 Python?
编辑:我仍然不明白如何splitlines()
不适合你:
>>> s = '''\
... First line, with LF\n\
... Second line, with CR\r\
... Third line, with CRLF\r\n\
... Two blank lines with LFs\n\
... \n\
... \n\
... Two blank lines with CRs\r\
... \r\
... \r\
... Two blank lines with CRLFs\r\n\
... \r\n\
... \r\n\
... Three blank lines with a jumble of things:\r\n\
... \r\
... \r\n\
... \n\
... End without a newline.'''
>>> s.splitlines()
['First line, with LF', 'Second line, with CR', 'Third line, with CRLF', 'Two blank lines with LFs', '', '', 'Two blank lines with CRs', '', '', 'Two blank lines with CRLFs', '', '', 'Three blank lines with a jumble of things:', '', '', '', 'End without a newline.']
>>> print '\n'.join(s.splitlines())
First line, with LF
Second line, with CR
Third line, with CRLF
Two blank lines with LFs
Two blank lines with CRs
Two blank lines with CRLFs
Three blank lines with a jumble of things:
End without a newline.
据我所知splitlines()
,不会将列表拆分两次或任何东西。
您可以粘贴给您带来麻烦的那种输入示例吗?