windows的换行是\r\n,unix的是\n,mac的是\r
open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, closefd=True)
在Python3,可以通过open函数的 newline参数来控制 Universal new line mode:读取时候,不指定newline,则默认开启Universal new line mode,所有\n, \r, or \r\n被默认转换为\n ;写入时,不指定newline,则换行符为各系统默认的换行符(\n, \r, or \r\n, ),指定为newline='\n',则都替换为\n(相当于Universal new line mode);不论读或者写时,newline=''都表示不转换。
在Python3,可以通过open函数的 newline参数来控制 Universal new line mode:读取时候,不指定newline,则默认开启Universal new line mode,所有\n, \r, or \r\n被默认转换为\n ;写入时,不指定newline,则换行符为各系统默认的换行符(\n, \r, or \r\n, ),指定为newline='\n',则都替换为\n(相当于Universal new line mode);不论读或者写时,newline=''都表示不转换。
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
- On input, 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. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
- On output, if newline is None, any '\n' characters written are translated to the system default line separator,os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.
file(fn, 'w+').write('test\ntest2') 改成file(fn, 'wb+').write('test\ntest2')就行了。Windows 平台上 Python 区分 Binary 和 ASCII 模式。ASCII 模式下换行符会在读写时自动换为 \r\n
转自知乎:http://www.zhihu.com/question/19751023/answer/12846261