Venkatraja K
Venkatraja K

Reputation: 21

TypeError: 'generator' object is not subscriptable in python

I am new to python, trying to learn.

I am using below code to read the excel spread sheet but getting below error. Can anyone help me with how to solve this? Or what is wrong with the code.

import openpyxl   
import os

if not os.path.isfile('C:\Python\Python36\EBC_N_Bhatt_Anilkumar _Team - 06132018.xlsx'):
    raise Exception('File does not exist.')

wb = openpyxl.load_workbook('C:\Python\Python36\EBC_N_Bhatt_Anilkumar _Team - 06132018.xlsx')    

sheet_ind = 0

sheet_names = wb.get_sheet_names()

sheet = wb.get_sheet_by_name(sheet_names[sheet_ind])

r = sheet.max_row

c = sheet.max_column

start_row = 0

for i in range(start_row, r):

cur_row = list(sheet.rows[i])

print(cur_row)

"C:\Users\KVenkataraja\PycharmProjects\Python Tutorials\venv\Scripts\python.exe" "C:/Users/KVenkataraja/PycharmProjects/Python Tutorials/readexel.py" C:/Users/KVenkataraja/PycharmProjects/Python Tutorials/readexel.py:9: DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames). sheet_names = wb.get_sheet_names() C:/Users/KVenkataraja/PycharmProjects/Python Tutorials/readexel.py:10: DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]). sheet = wb.get_sheet_by_name(sheet_names[sheet_ind]) Traceback (most recent call last): File "C:/Users/KVenkataraja/PycharmProjects/Python Tutorials/readexel.py", line 18, in cur_row = list(sheet.rows[i])

TypeError: 'generator' object is not subscriptable

Process finished with exit code 1

Upvotes: 2

Views: 11998

Answers (1)

Rahul Goswami
Rahul Goswami

Reputation: 595

sheet.rows probably (as your error message suggests) is a generator of rows, that's why it is not sub-scriptable. You should iterate over the generator sheet.rows.

You can, and should iterate it as in the following code snippet:

for row in sheet.rows:
    cur_row = list(row)
    print(cur_row)

Or if you want the index too, then use enumerate,

for index, row in enumerate(sheet.rows):
    cur_row = list(row)
    print(cur_row)
    # print(index)

Upvotes: 5

Related Questions