0

I am trying to convert multiple .xls files into one .csv file so i can use in a later script.

I found most of this code in other Stackoverflow pages but when trying to run the code below i get the following error:

Error:

Traceback (most recent call last):
  File "script_base_teste.py", line 13, in <module>
    wr.writerow(sh.row_values(rownum))
TypeError: a bytes-like object is required, not 'str'

Code:

import xlrd
import csv


for num in range(1,4):

    wb = xlrd.open_workbook("file"+str(num)+".xls")
    sh = wb.sheet_by_name("Sheet 1")
    your_csv_file = open("file"+str(num)+".csv", "wb")
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(0,sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()




fout=open("result.csv","a")
first file:
for line in open("file1.csv"):
    fout.write(line)
now the rest:    
for num in range(2,3):
    f = open("file"+str(num)+".csv")
    f.next() # skip the header
    for line in f:
         fout.write(line)
    f.close()
fout.close()

I'm using Python3 and I got most of the code from this and this

1 Answers1

0

You opened the file in binary mode

your_csv_file = open("file"+str(num)+".csv", "wb")

The "wb" stands for "write binary". You can only read/write binary data in this mode. Since you want to write using strings, you can open it in write mode, using "w" instead of "wb".

your_csv_file = open("file"+str(num)+".csv", "w")
  • That somewhat worked but now i get the following error: Traceback (most recent call last): File "script_base_teste.py", line 13, in wr.writerow(sh.row_values(rownum)) File "C:\Users\ycunhafe\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\ufeff' in position 685: character maps to – Otorrinolaringologista -man Dec 26 '17 at 19:45