TypeError: 'list' object is not callable, reading from excel sheet

Question:

I am tring to read a very simple excel sheet. And I have this to read the excel sheet:

import xlrd
import pandas

workbook=pandas.ExcelFile(r'C:UsersDocumentspythondocsBook1.xlsx', engine='openpyxl')
sh=workbook.sheet_names(0)
print(sh.rows) 
print (sh.ncols)
n=0
i=0
file=open("xxx.txt","w")
for n in range(sh.nrows):
    for i in range(sh.ncols):
        data =sh.cell_value(n,i)+" "
        print (data),
        file.write(data+" ")
    print 
    file.write("n")

But I get this error:

Traceback (most recent call last):
  File "c:UsersDocumentspythoncodetextFromExcel.py", line 5, in <module>
    sh=workbook.sheet_names(0)
TypeError: 'list' object is not callable

So my question is: How to resolve this?

Thank you

Yes. But if I do this:

import xlrd
import pandas

workbook=pandas.ExcelFile(r'C:UsersengelDocumentspythondocsBook1.xlsx', engine='openpyxl')
sh=workbook.sheet_names[0]
print(sh.rows) 
print (sh.ncols)
n=0
i=0
file=open("xxx.txt","w")
for n in range(sh.nrows):
    for i in range(sh.ncols):
        data =sh.cell_value(n,i)+" "
        print (data),
        file.write(data+" ")
    print 
    file.write("n")

Then I get this error:

File "c:UsersengelDocumentspythoncodetextFromExcel.py", line 6, in <module>
    print(sh.rows)
AttributeError: 'str' object has no attribute 'rows'
Asked By: mightycode Newton

||

Answers:

From the perspective or writing code, the shortest way to read a file would be using pandas.read_excel(filename, sheetname) as this would read the whole sheet directly into a pandas dataframe in one shot.

import pandas as pd
df = pd.read_excel('Readfile.xlsx','Sheet1')
print(df)

To write the contents of the dataframe into a file, use to_excel().

import pandas a pd
df.to_excel('OutputFile.xlsx','Sheet1')

Note that if the file already exists and there is data in Sheet1, this will overwrite the data there. You can overlay the new data on top of existing data using overlay in newer versions. Check this link if that is your requirement.

Answered By: Redox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.