python二进制创建写模式_Python 2和3 csv模块文本二进制模式向后兼容
在python3上打开要与模块csv一起使用的文件时,always应该添加newline=""open语句:import sys
mode = 'w'
if sys.version_info[0] < 3:
mode = 'wb'
# python 3 write
with open("somefile.txt", mode, newline="") as f:
pass # do something with f
python2中不存在newline参数,但如果在python3中跳过它,则会在windows上得到变形错误的csv输出,其中有额外的空行。在If csvfile is a file object, it should be opened with newline=''. If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.
您还应该使用contextmanaging with:
^{pr2}$
即使遇到某种异常,也要关闭文件句柄。这是python 2的安全-请参见Methods of file objects:It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.
你的解决方案-丑陋但有效:import sys
python3 = sys.version_info[0] >= 3
if python3:
with open("somefile.txt","w",newline="") as f:
pass
else:
with open("somefile.txt","wb") as f:
pass
问题是python2中不存在参数newline。要解决这个问题,您必须包装/monkypathopen(..),包括contextmanagement。在