- 在Python 2中:始终以二进制模式打开文件。
csv.DictWriter()
写rn
行尾:with open(filename, 'ab') as outputfile:writer = csv.DictWriter(outputfile, fieldnames)
从
csv.writer()文档中:
如果 csvfile 是文件对象,则必须在有区别的平台上使用“ b”标志打开它。
- 在Python 3中:使用打开文件,
newline=''
因此csv.DictWriter()
可以控制无需翻译而编写的换行符:with open(filename, 'a', newline='') as outputfile:writer = csv.DictWriter(outputfile, fieldnames)
再次引用相关
csv.writer()文档:
如果 csvfile 是文件对象,则应使用
newline=''[…]
如果
newline=''未指定,嵌入引号字段中的换行符将无法正确解释,并且在使用rnlinendings的平台r上将添加额外的字符。newline=''由于csv模块会执行自己的(通用)换行处理,因此始终应该安全地指定。



