-1

Below code is working fine in Unix and while trying to make it work in windows it's failing - I am trying to create excel after joining multiple csv files in a directory . Tab names in excel should be the csv filename -

Below is the code

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)

Error -

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

Any suggestion please ? Complete output -

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?)
martineau
  • 119,623
  • 25
  • 170
  • 301
Pratik Rudra
  • 37
  • 1
  • 7

1 Answers1

0

Correct code -

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)

Not sure why 'rb' works in Unix but not in Windows

Pratik Rudra
  • 37
  • 1
  • 7