Python写入CSV ... TypeError:强制转换为Unicode:需要字符串或缓冲区,找到文件 [英] Python writing to CSV... TypeError: coercing to Unicode: need string or buffer, file found
问题描述
outputList是列表的列表. [[a,b,c],[d,e,f],[g,h,i]],我想将其输出到一个csv文件,每个列表作为单独的一行.我收到此错误TypeError:强制转换为Unicode:需要字符串或缓冲区,找到的文件,但我不知道为什么.我使用的是python 2.7和最新的mac.在我的代码下方,在此先感谢
outputList is a list of lists. [ [a,b,c], [d,e,f], [g,h,i] ] and I want to output it to a csv file with each list as a separate row. I'm getting this error TypeError: coercing to Unicode: need string or buffer, file found and I dont know why. Im using python 2.7 and a newish mac. Belows my code, thanks in advance
f2 = open(os.path.expanduser("~/Documents/Test/blah/outputfile.csv"))
with open(f2, 'w') as fp:
a = csv.writer(fp)
for row in zip(outputList) :
a.writerow(row)
f2.close()
推荐答案
f2
已经已经一个打开的文件对象;您调用了open()
函数:
f2
is already an open file object; you called the open()
function:
f2 = open(os.path.expanduser("~/Documents/Test/blah/outputfile.csv"))
然后不能将其传递给open()
.我认为您的意思只是一个文件名:
You cannot then pass that to open()
. I think you meant it to be just a filename:
f2 = os.path.expanduser("~/Documents/Test/blah/outputfile.csv")
with open(f2, 'w') as fp:
这篇关于Python写入CSV ... TypeError:强制转换为Unicode:需要字符串或缓冲区,找到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!