Python在windows下生成excel失败

问题描述 投票:-1回答:1

下面的代码在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?)
python xlwt
1个回答
0
投票

正确的代码 -

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中却不能用。

© www.soinside.com 2019 - 2024. All rights reserved.