在windows中生成Python excel失败

在windows中生成Python excel失败,python,xlwt,Python,Xlwt,下面的代码在Unix中运行良好,但在windows中尝试运行时失败了- 我试图在将多个csv文件合并到一个目录中后创建excel。 excel中的选项卡名称应为csv文件名- 下面是代码 def create_Excel(path,output_file): print("Input path is " + path) print("Output File name " + output_file ) wb = xlwt.Workbook() for csvfile in glob(os

下面的代码在Unix中运行良好,但在windows中尝试运行时失败了- 我试图在将多个csv文件合并到一个目录中后创建excel。 excel中的选项卡名称应为csv文件名-

下面是代码

def create_Excel(path,output_file):
 print("Input path is " + path)
 print("Output File name " + output_file )
 wb = xlwt.Workbook()
 for csvfile in glob(os.path.join(path, '*.csv')):
   fpath = csvfile.split("/", 1)
   print ("Current Path " + csvfile )
   fname = fpath[1].split("\\", 2)
   print(str(fname)[1:-1] )
   print ("Current Filename... " + fname[1].split(".",1)[0] )
   ws = wb.add_sheet( fname[1].split(".",1)[0] )
   with open(csvfile, 'rb') as f:
     reader = csv.reader(f)
     for r, row in enumerate(reader):
       for c, col in enumerate(row):
         ws.write(r, c, col)
   wb.save(output_file)
错误-

_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
有什么建议吗? 完整输出-

Output File name INFA_XML.xls
Current Path C:/TEMP/Output\aggregator.csv
'TEMP/Output', 'aggregator.csv'
Current Filename... aggregator
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 14, in create_Excel
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
输出文件名INFA_XML.xls
当前路径C:/TEMP/Output\aggregator.csv
“临时/输出”、“聚合器.csv”
当前文件名。。。聚合器
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
创建Excel中第14行的文件“”
_错误:迭代器应该返回字符串,而不是字节(您是否以文本模式打开了文件?)
正确的代码-

def create_Excel(path,output_file):
 print("Input path is " + path)
 print("Output File name " + output_file )
 wb = xlwt.Workbook()
 for csvfile in glob(os.path.join(path, '*.csv')):
  fpath = csvfile.split("/", 1)
  print ("Current Path " + csvfile )
  fname = fpath[1].split("\\", 2)
  print(str(fname)[1:-1] )
  print ("Current Filename... " + fname[1].split(".",1)[0] )
  ws = wb.add_sheet( fname[1].split(".",1)[0] )
  with open(csvfile, 'rt') as f:
    reader = csv.reader(f)
    for r, row in enumerate(reader):
      for c, col in enumerate(row):
        print("Writing to excel .....")
        ws.write(r, c, col)
  wb.save(output_file)

不确定为什么“rb”在Unix中工作,但在Windows中不工作

为什么在打开
csvfile
时使用
“rb”
?您以文本模式打开了文件。问题已经解决了,这是否回答了您的问题@Billeleuch:文件需要以文本模式打开(正如链接答案所解释的);这段代码不能做到这一点。