TypeError: 'ExcelData' object is not iterable

本文记录了一次在Python中从Excel读取数据时遇到的TypeError异常,并分享了解决过程。通过检查调用方法的方式,最终定位问题所在,即未正确调用readExcle方法导致返回值错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天写了个测试的代码,结果在执行test_register.py文件在调用readexcle.py的时候一直报错TypeError: 'ExcelData' object is not iterable,最后发现是test_register.py模块调用readexcle.py模块时,忘记调用方法了,导致返回值有误,折腾了半天,是个教训。

 下面是readexcle.py模块(读取excle内的数据并返回读取到的数据):

 1 import xlrd
 2 
 3 class ExcelData():
 4     def __init__(self,data_path,sheetname):
 5         self.data_path = data_path                                 # excle表格路径
 6         self.sheetname = sheetname                                 # excle表格内sheet
 7         self.data = xlrd.open_workbook(self.data_path)             # 打开excle表格
 8         self.table = self.data.sheet_by_name(self.sheetname)       # 切换到相应sheet
 9         self.keys = self.table.row_values(0)                       # 第一行作为key值
10         self.rowNum = self.table.nrows                             # 获取表格行数
11         self.colNum = self.table.ncols                             # 获取表格列数
12         # print(self.rowNum)
13         # print(self.colNum)
14 
15     def readExcle(self):
16         if self.rowNum<2:
17             print("excle内数据行数小于2")
18         else:
19             L = []
20             for i in range(1,self.rowNum):
21                 sheet_data = {}
22                 for j in range(self.colNum):
23                     sheet_data[self.keys[j]] = self.table.row_values(i)[j]
24                 L.append(sheet_data)
25             #print(type(L))
26             return L
27 
28 if __name__ == '__main__':
29     data_path = "F:\\KEJINSUO_interface\\Case\\interface_data.xlsx"
30     sheetname = "注册"
31     get_data = ExcelData(data_path,sheetname)
32     print(get_data.readExcle())

 

下面是test_register.py模块(调用readexcle.py模块,使用readexcle.py返回值做参数):

 1 import requests
 2 import json
 3 import unittest
 4 from readexcle import ExcelData
 5 
 6 class Regist(unittest.TestCase):
 7     def setUp(self):
 8         self.headers = {"Content-Type":"application/json"}
 9         self.data_path = "F:\\KEJINSUO_interface\\Case\\interface_data.xlsx"
10         self.sheetname = "注册"
11         self.shuju = ExcelData(self.data_path,self.sheetname).readExcle()        #错误在此行,未调用readExcle方法  
12 
13     def test_regist(self):
14         for a in self.shuju:
15              self.url = "http://test.jkkjs.cn:44444/api/register/createUser"
16              self.pars = {"data": {
17                          "mobile":a['mobile'],
18                           "password": a['password'],
19                           "verifyCode":a['verifyCode']
20                           }
21              }
22              self.par_json = json.dumps(self.pars)
23              res = requests.post(self.url,data=self.par_json,headers=self.headers)
24              #根据返回数据判断登录结果
25              if "注册成功" in res.text:
26                   print("注册成功")
27              elif "手机号码已注册" in res.text:
28                   print("手机号码已注册")
29              elif "参数错误" in res.text:
30                   print("提交参数错误")

 

转载于:https://www.cnblogs.com/kakaln/p/8144538.html

PS D:\a\b\PythonProject1> pytest -s ========================================================================= test session starts ========================================================================= platform win32 -- Python 3.11.9, pytest-7.4.0, pluggy-1.6.0 rootdir: D:\a\b\PythonProject1 configfile: pytest.ini testpaths: test_test/ plugins: metadata-3.1.1, parallel-0.1.1, repeat-0.9.4, testreport-1.1.6, xdist-3.8.0 collecting ... D:\a\b\PythonProject1 {'api_name': '用户登录', 'url': 'https://10.121.177.71/itf/session', 'method': 'post', 'verify': 'verify', 'headers': {'Content-Type': 'application/x-www-form-urlencoded'}} collected 3 items test_test\test_api.py 请求头参数: {'Content-Type': 'application/x-www-form-urlencoded'} 参数类型:data 请求参数:{"username": "admin", "password": "admin"} 接口返回值: { "ResidueDay": 255, "ok": 0, "privilege": 4, "user_id": 2, "extendedpriv": 383, "racsession_id": 48, "remote_addr": "10.121.178.218", "server_name": "10.1 .71", "server_addr": "10.121.177.71", "HTTPSEnabled": 1, "CSRFToken": "SN3nPzFG", "channel": 1, "passwordStatus": 0, "encrypt_flag": 0, "SelfSetPriv": 1, "InfoQue e ryPriv": 1, "DebugPriv": 1, "PowerConPriv": 1, "SecuConPriv": 1, "RemoteMediaPriv": 1, "RemoteKVMPriv": 1, "CommConfigPriv": 1, "UserConfigPriv": 1, "group_name": "Administrator", "ChangePasswordAlert": 0 } 状态吗断言成功:接口实际返回状态码200 == 200 测试成功 . 请求头参数: {'Content-Type': 'application/x-www-form-urlencoded'} 参数类型:data 请求参数:{"username": "admin", "password": "admin"} 接口返回值: { "ResidueDay": 255, "ok": 0, "privilege": 4, "user_id": 2, "extendedpriv": 383, "racsession_id": 49, "remote_addr": "10.121.178.218", "server_name": "10.1 21.177.71", "server_addr": "10.121.177.71", "HTTPSEnabled": 1, "CSRFToken": "uRz7lMlP", "channel": 1, "passwordStatus": 0, "encrypt_flag": 0, "SelfSetPriv": 1, "InfoQue ryPriv": 1, "DebugPriv": 1, "PowerConPriv": 1, "SecuConPriv": 1, "RemoteMediaPriv": 1, "RemoteKVMPriv": 1, "CommConfigPriv": 1, "UserConfigPriv": 1, "group_name": "Administrator", "ChangePasswordAlert": 0 } 出现异常,--'NoneType' object is not iterable F 请求头参数: {'Content-Type': 'application/x-www-form-urlencoded'} 参数类型:data 请求参数:{"username": "admin", "password": "admin"} 接口返回值: { "ResidueDay": 255, "ok": 0, "privilege": 4, "user_id": 2, "extendedpriv": 383, "racsession_id": 50, "remote_addr": "10.121.178.218", "server_name": "10.1 21.177.71", "server_addr": "10.121.177.71", "HTTPSEnabled": 1, "CSRFToken": "s4fPh5ra", "channel": 1, "passwordStatus": 0, "encrypt_flag": 0, "SelfSetPriv": 1, "InfoQue ryPriv": 1, "DebugPriv": 1, "PowerConPriv": 1, "SecuConPriv": 1, "RemoteMediaPriv": 1, "RemoteKVMPriv": 1, "CommConfigPriv": 1, "UserConfigPriv": 1, "group_name": "Administrator", "ChangePasswordAlert": 0 } 出现异常,--'NoneType' object is not iterable F ============================================================================== FAILURES =============================================================================== ________________________________________________________ TestLogin.test_login_module[api_info0-testcase0-2-3] _________________________________________________________ self = <test_test.test_api.TestLogin object at 0x00000198BD875810> api_info = {'api_name': '用户登录', 'headers': {'Content-Type': 'application/x-www-form-urlencoded'}, 'method': 'post', 'url': 'https://10.121.177.71/itf/session', ...} testcase = {'data': {'password': 'admin', 'username': 'admin'}} @pytest.mark.passdef @pytest.mark.repeat(3) @pytest.mark.parametrize('api_info,testcase', YamlUtil().read_def_yaml('get_new.yaml')) def test_login_module(self, api_info, testcase): if 'case_name' not in testcase: testcase['case_name'] = f"默认用例_{id(testcase)}" # 用唯一标识避免重复 > RequestsBase().execute_test_cases(api_info, testcase) test_test\test_api.py:14: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ unit_tools\apiutils_single.py:121: in execute_test_cases raise e unit_tools\apiutils_single.py:117: in execute_test_cases self.asserts.assert_result(validation,response.json(),status_code) unit_tools\assertion_utils.py:124: in assert_result raise exceptions _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cls = <class 'unit_tools.assertion_utils.Assertions'>, expected_result = None response = {'CSRFToken': 'uRz7lMlP', 'ChangePasswordAlert': 0, 'CommConfigPriv': 1, 'DebugPriv': 1, ...}, status_code = 200 @classmethod def assert_result(cls, expected_result, response, status_code): """ 断言主函数,通过all_flag标记,如all_flag == 0表示测试成功,否则为失败 :param expected_result: (list)yaml文件validation关键词下面的预期结果 :param response: (dict)接口的实际响应信息 :param status_code: (int)接口的实际响应状态码 :return: """ all_flag = 0 # 通过字典映射方式管理不同的断言方式 assert_methods = { 'code': cls.status_code_assert, 'contain': cls.contain_assert, 'eq': cls.equal_assert # 'ne': cls.not_equal_assert, } try: > for yq in expected_result: E TypeError: 'NoneType' object is not iterable unit_tools\assertion_utils.py:109: TypeError ________________________________________________________ TestLogin.test_login_module[api_info0-testcase0-3-3] _________________________________________________________ self = <test_test.test_api.TestLogin object at 0x00000198BD877F50> api_info = {'api_name': '用户登录', 'headers': {'Content-Type': 'application/x-www-form-urlencoded'}, 'method': 'post', 'url': 'https://10.121.177.71/itf/session', ...} testcase = {'data': {'password': 'admin', 'username': 'admin'}} @pytest.mark.passdef @pytest.mark.repeat(3) @pytest.mark.parametrize('api_info,testcase', YamlUtil().read_def_yaml('get_new.yaml')) def test_login_module(self, api_info, testcase): if 'case_name' not in testcase: testcase['case_name'] = f"默认用例_{id(testcase)}" # 用唯一标识避免重复 > RequestsBase().execute_test_cases(api_info, testcase) test_test\test_api.py:14: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ unit_tools\apiutils_single.py:121: in execute_test_cases raise e unit_tools\apiutils_single.py:117: in execute_test_cases self.asserts.assert_result(validation,response.json(),status_code) unit_tools\assertion_utils.py:124: in assert_result raise exceptions _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cls = <class 'unit_tools.assertion_utils.Assertions'>, expected_result = None response = {'CSRFToken': 's4fPh5ra', 'ChangePasswordAlert': 0, 'CommConfigPriv': 1, 'DebugPriv': 1, ...}, status_code = 200 @classmethod def assert_result(cls, expected_result, response, status_code): """ 断言主函数,通过all_flag标记,如all_flag == 0表示测试成功,否则为失败 :param expected_result: (list)yaml文件validation关键词下面的预期结果 :param response: (dict)接口的实际响应信息 :param status_code: (int)接口的实际响应状态码 :return: """ all_flag = 0 # 通过字典映射方式管理不同的断言方式 assert_methods = { 'code': cls.status_code_assert, 'contain': cls.contain_assert, 'eq': cls.equal_assert # 'ne': cls.not_equal_assert, } try: > for yq in expected_result: E TypeError: 'NoneType' object is not iterable unit_tools\assertion_utils.py:109: TypeError ========================================================================== warnings summary =========================================================================== test_test/test_api.py::TestLogin::test_login_module[api_info0-testcase0-1-3] test_test/test_api.py::TestLogin::test_login_module[api_info0-testcase0-2-3] test_test/test_api.py::TestLogin::test_login_module[api_info0-testcase0-3-3] D:\python\Lib\site-packages\urllib3\connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '10.121.177.71'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings warnings.warn( -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ======================================================================= short test summary info ======================================================================= FAILED test_test/test_api.py::TestLogin::test_login_module[api_info0-testcase0-2-3] - TypeError: 'NoneType' object is not iterable FAILED test_test/test_api.py::TestLogin::test_login_module[api_info0-testcase0-3-3] - TypeError: 'NoneType' object is not iterable =============================================================== 2 failed, 1 passed, 3 warnings in 2.34s =============================================================== PS D:\a\b\PythonProject1> 如何解决该问题
最新发布
08-06
import pandas as pd from openpyxl import Workbook # 获取主题下词语的概率分布 def get_topic_word_distribution(lda, tf_feature_names): arr = lda.transform(tf_vectorizer.transform([' '.join(tf_feature_names)])) return arr[0] # 打印主题下词语的概率分布 def print_topic_word_distribution(lda, tf_feature_names, n_top_words): dist = get_topic_word_distribution(lda, tf_feature_names) for i in range(lda.n_components): print("Topic {}: {}".format(i, ', '.join("{:.4f}".format(x) for x in dist[i]))) # 输出每个主题下词语的概率分布至Excel表格 def output_topic_word_distribution_to_excel(lda, tf_feature_names, n_top_words,filename): # 创建Excel工作簿和工作表 wb = Workbook() ws = wb.active ws.title = "Topic Word Distribution" # 添加表头 ws.cell(row=1, column=1).value = "Topic" for j in range(n_top_words): ws.cell(row=1, column=j+2).value = tf_feature_names[j] # 添加每个主题下词语的概率分布 dist = get_topic_word_distribution(lda, tf_feature_names) for i in range(lda.n_components): ws.cell(row=i+2, column=1).value = i for j in range(n_top_words): ws.cell(row=i+2, column=j+2).value = dist[i][j] # 保存Excel文件 wb.save(filename) n_top_words = 30 tf_feature_names = tf_vectorizer.get_feature_names() topic_word = print_topic_word_distribution(lda, tf_feature_names, n_top_words)报错Traceback (most recent call last): File "D:\python\lda3\data_1.py", line 157, in <module> topic_word = print_topic_word_distribution(lda, tf_feature_names, n_top_words) File "D:\python\lda3\data_1.py", line 130, in print_topic_word_distribution print("Topic {}: {}".format(i, ', '.join("{:.4f}".format(x) for x in dist[i]))) TypeError: 'numpy.float64' object is not iterable
05-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值