【发布时间】:2019-10-05 22:56:36
【问题描述】:
我想创建一个与 Python 2.7-3.6 兼容的代码 我正在尝试解决 csv 模块的问题,我最初在 Python 2.7 中使用 outfile=open('./test.csv','wb') 现在我必须使用 outfile=open('./test.csv','w') like in this question 否则我会招致一个
TypeError: a bytes-like object is required, not 'str'.
我正在使用此代码修复它的那一刻:
import sys
w = 'w'
if sys.version_info[0] < 3:
w = 'wb'
# Where needed
outfile=open('./test.csv',w)
不是很好,如果我使用 Python 2.7 和 w 如果我使用 Python 3.x,是否有更好的解决方案可以在“wb”中打开文件?为了澄清,我必须在 Python 2.7 中使用 wb,否则,每次向文件添加新行时都会有一个空行。
【问题讨论】:
标签: python python-3.x python-2.7 csv backwards-compatibility