0

I'm getting this error "SyntaxError: multiple statements found while compiling a single statement" when trying to import xlrd in python on Windows.

I have installed the newest version xlrd and python(3.7.0). Can you please help me figure out what the problem is?

import xlrd
import unicodecsv

def xls2csv (sheet1.xlsx, sheet1.csv):

    wb = xlrd.open_workbook(sheet1.xlsx)
    sh = wb.sheet_by_index(2)

    fh = open(sheet1.csv,"wb")
    csv_out = unicodecsv.writer(fh, encoding='utf-8')

    for row_number in xrange (sh.nrows):
        csv_out.writerow(sh.row_values(row_number))

    fh.close()
Pixeline
  • 11
  • 1
  • Show us the full traceback, not just the error message. We need to see the line of code that the interpreter is complaining about. Edit your question to include this: don't put it in a comment. This line: `def xls2csv (sheet1.xlsx, sheet1.csv):` is a syntax error because function arguments can't have dots in them. But that is a different syntax error from the one you report. You will get that error if you simply paste your code into IDLE at a `>>>` prompt. That is not how IDLE works. If you want it to execute Python code in a file, use `File|Open`. – BoarGules Jan 21 '21 at 09:27
  • From your code it appears that you are following a Python 2 example but are trying to get it to run in Python 3. `xrange()` and `unicodecsv` don't exist in Python 3. Use `range()` and `csv` instead. Better still, dump your how-to and look for one that isn't 10 years out of date. – BoarGules Jan 21 '21 at 09:37

2 Answers2

1

I ended up doing this and now it works! Thanks for your help though.

import xlrd
import unicodecsv

book = xlrd.open_workbook("test.xls")
sheet = book.sheet_by_index(0)


try:
    fh = open("test.csv","wb")
    csv_out = unicodecsv.writer(fh, encoding='utf-8')
except:
    print ("Something is wrong..")


for row_number in range (sheet.nrows):
    csv_out.writerow(sheet.row_values(row_number))
    fh.close()
Pixeline
  • 11
  • 1
0

I think XLRD works only for .xls files.as you have given to open .csv file I think it might be causing error for that reason..Change the file type to .xls in the msword.

I'm not sure with the answer but try once by changing the file type to .xls.

sreekanth
  • 11
  • 4
  • I've tried to change the file endings to .xls already and I still get the error "SyntaxError: multiple statements found while compiling a single statement". – Pixeline Jan 21 '21 at 09:20