2.7 CSV模块需要unicode,但不需要unicode

Kel*_*oll 12 python csv unicode error-handling python-2.7

csvfile_ = open(finishedFileName+num+".csv","w",newline='')
writ = csv.writer(csvfile_, dialect='excel')
firstline = unicode(str(firstline))
try:
    writ.writerow(firstline)
except TypeError:
    print firstline
    print type(firstline)
    raise
Run Code Online (Sandbox Code Playgroud)

我得到了TypeError: must be unicode, not str这个代码.当我打印出第一线的类型时<type 'unicode'>.当我打印第一行时,我看到['project_number', 'project_location'](列表比这长,但它继续以那种风格.)

这个程序在python 3.3中运行良好.我用3to2移植它,从我这样做,从unix切换到windows.

如何使这个程序顺利写入?

注意:根据官方文档,此版本的csv模块不支持Unicode输入,但它告诉我无论如何都要给它输入Unicode.

完全例外

Traceback (most recent call last):
  File "C:\Users\urightswt\Downloads\LogModToConvert.py", line 382, in <module>
    process(marketingLogExportFileName)
  File "C:\Users\urightswt\Downloads\LogModToConvert.py", line 123, in process
    writing(csvfile,modified,firstline)
  File "C:\Users\urightswt\Downloads\LogModToConvert.py", line 114, in writing
    writ.writerow(firstline)
TypeError: must be unicode, not str
Run Code Online (Sandbox Code Playgroud)

如果我拿出代码来制作第一行unicode,我会得到

Traceback (most recent call last):
  File "C:\Users\urightswt\Downloads\LogModToConvert.py", line 382, in <module>
    process(marketingLogExportFileName)
  File "C:\Users\urightswt\Downloads\LogModToConvert.py", line 123, in process
    writing(csvfile_,modified,firstline)
  File "C:\Users\urightswt\Downloads\LogModToConvert.py", line 114, in writing
    writ.writerow(firstline)
TypeError: must be unicode, not str
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 17

不幸的是,3to2使用了io.open()调用而不是内置的Python 2 open()函数.这以文本模式打开文件,就像在Python 3上一样,需要Unicode输入.

但是,该csv模块不支持Unicode数据; 它肯定不会产生Unicode.

你要么必须在Python 2上以二进制模式打开文件:

mode = 'w'
if sys.version_info.major < 3:
    mode += 'b'
csvfile_ = open(finishedFileName + num + ".csv", mode, newline='')
Run Code Online (Sandbox Code Playgroud)

或者使用内置open()调用:

csvfile_ = open(finishedFileName + num + ".csv", 'wb')
Run Code Online (Sandbox Code Playgroud)

'wb'无论如何你必须用作模式.

如果您正在尝试写出unicode数据,则必须在将数据传递给对象之前对其进行编码csv.writer().的csv模块实施例部分包括代码以使从Unicode编码写入更容易一些之前.