获取变量错误-在此Python代码中可能未定义Mytable和tableName。如何纠正这一点?

获取变量错误-在此Python代码中可能未定义Mytable和tableName。如何纠正这一点?,python,pycharm,Python,Pycharm,我得到了变量错误-Mytable和tableName在此Python代码中可能未定义。如何纠正这一点 import pyodbc # we may be interested in finding all the drivers we have access to for driver in pyodbc.drivers(): # print the driver name # print(driver) # if the driver name has '.xlsx' in it we

我得到了
变量错误-Mytable和tableName在此Python代码中可能未定义。如何纠正这一点

import pyodbc

# we may be interested in finding all the drivers we have access to
for driver in pyodbc.drivers():

# print the driver name
# print(driver)

# if the driver name has '.xlsx' in it we found it!
if '.xlsx' in driver:
    myDriver = driver

# define our connection string
conn_str = (r'DRIVER={' + myDriver + '};'
                                 r'DBQ="C:\Python_Project\Tap Report for 26-Aug-2022.xlsx;'
                                 r'ReadOnly=1')  # ReadOnly set to 0 means we can edit the data.

# define our connection, autocommit MUST BE SET TO TRUE, also we can edit data.
cnxn = pyodbc.connect(conn_str, autocommit=True)
crsr = cnxn.cursor()

# loop through all the tables
for worksheet in crsr.tables():
     # display the worksheet
     print(worksheet)

     # grab the table name.
     tableName = worksheet[2]

# define our query to grab the data.
# we want this "SELECT Topic FROM [Sheet1$]"
crsr.execute("SELECT Topic FROM [{}]".format(tableName))

# print each row of data.
for row in crsr:
     print(row.Topic)

请更正代码的缩进。Python对缩进非常敏感,Python程序员也是如此。我已经更新了缩进。这次看起来还好吗。?抱歉出现任何错误。此代码中没有
Mytable
,而对于
tableName
,如果循环根本没有运行(
crsr.tables()
为空),则不会定义
tableName
。您可能希望使用该情况下的默认值对其进行初始化,或者将
crsr.execute()
行作为loopYes的一部分。很抱歉,变量名是myDriver您对myDriver和tableName都有相同的问题。您没有修复缩进。如果你有,就更容易看到了。