文件读写

转载自:http://blog.csdn.net/pfm685757/article/details/47806469

如果不带newline=‘’,你会发现也能写入结果,但是每行内容之间总是会多出一个空行

下面是python参考手册里的解释,在windows这种使用\r\n的系统里,不用newline=‘’的话,会自动在行尾多添加个\r,导致多出一个空行,即行尾为\r\r\n
In Python 2.X, it was required to open the csvfile with 'b' because the csv module does its own line termination handling.
In Python 3.X, the csv module still does its own line termination handling, but still needs to know an encoding for Unicode strings. The correct way to open a csv file for writing is:

outputfile=open("out.csv",'w',encoding='utf8',newline='') 

encoding can be whatever you require, but newline='' suppresses text mode newline handling. On Windows, failing to do this will write \r\r\n file line endings instead of the correct \r\n. This is mentioned in the 3.X csv.reader documentation only, but csv.writer requires it as well.

你可能感兴趣的:(文件读写)