Home > Software engineering >  TypeError: 'list' object is not callable, reading from excel sheet
TypeError: 'list' object is not callable, reading from excel sheet

Time:09-01

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:\Users\Documents\python\docs\Book1.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:\Users\Documents\python\code\textFromExcel.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:\Users\engel\Documents\python\docs\Book1.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:\Users\engel\Documents\python\code\textFromExcel.py", line 6, in <module>
    print(sh.rows)
AttributeError: 'str' object has no attribute 'rows'

CodePudding user response:

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.

  • Related