错误:当从文本转换csv时,迭代器应返回字符串,而不是字节(在文本模式下打开文件吗?)

时间:2018-01-08 18:53:45

标签: python

我尝试运行此代码:

txt_file = r"Fun.txt"
in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\t')
csv_file = r"NewProcessedDoc.csv"
with open(csv_file, 'w', newline ='') as csvfile:
    swriter = csv.writer(csvfile, delimiter = ' ')
    swriter.writerow(in_txt)
print('done! Check NewProcessedDoc.csv file')

但有错误:

swriter.writerow(in_txt)

Error: iterator should return strings, not bytes (did you open the file in text mode?)

有人可以帮忙吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

  • 以文本模式打开文件:...open(txt_file, "rb")
  • 使用.writerows()方法而不是.writerow()swriter.writerows(in_txt)