使用csv.reader读取多CSV文件查找'error'时遇TypeError问题求助
问题分析与修复
错误根源
你触发的TypeError是因为参数类型不匹配:
find_cell函数的第一个参数csv_file被设计成接收文件路径(字符串/PathLike对象),因为函数内部会执行open(csv_file)来打开文件。- 但你在
errorCheck里,把已经创建好的csv.reader实例传给了find_cell,这就导致函数试图打开一个reader对象而非文件路径,自然报错。
另外代码里还有两个小问题:
print_and_log函数未定义,运行时会触发NameError;- 字符串拼接时用
{row_idx}是语法错误,应该转换成字符串str(row_idx)。
修复方案(两种可选)
方案一:修改find_cell接收reader对象(更高效,避免重复打开文件)
直接让find_cell处理已经创建好的csv.reader实例,不需要再打开文件:
import glob import os import csv import pathlib # 补充定义缺失的print_and_log函数,示例实现 def print_and_log(msg): print(msg) # 可在此添加写入日志文件的逻辑 def find_cell(reader, check): for row_idx, row in enumerate(reader): for col_idx, cell in enumerate(row): if cell == check: return row_idx, col_idx return None def errorCheck(Filename): is_match = False with open(Filename, 'r') as f: csv_reader = csv.reader(f, delimiter='|') check = 'Error' cell_location = find_cell(csv_reader, check) if cell_location: row_idx, col_idx = cell_location print("ERROR") print_and_log(f'ERROR IN FILE - {Filename} row {row_idx} column {col_idx}') is_match = True if is_match: return
方案二:保持find_cell接收文件路径,调整调用逻辑
如果不想修改find_cell的结构,调用时直接传文件名即可,无需提前创建reader:
import glob import os import csv import pathlib def print_and_log(msg): print(msg) def find_cell(csv_file, check): with open(csv_file,'r') as file: # 注意添加和调用处一致的分隔符|,避免解析错误 reader = csv.reader(file, delimiter='|') for row_idx, row in enumerate(reader): for col_idx, cell in enumerate(row): if cell == check: return row_idx, col_idx return None def errorCheck(Filename): is_match = False check = 'Error' cell_location = find_cell(Filename, check) if cell_location: row_idx, col_idx = cell_location print("ERROR") print_and_log(f'ERROR IN FILE - {Filename} row {row_idx} column {col_idx}') is_match = True if is_match: return
关键点说明
- 方案一更合理,因为
errorCheck已经打开了文件,没必要在find_cell里重复打开,能节省IO资源; - CSV文件的分隔符要统一,你在
errorCheck里用了delimiter='|',如果用方案二,find_cell里的csv.reader必须加上同样的分隔符,否则解析会出错; - 字符串拼接建议用f-string(
f'xxx{var}xxx'),比直接拼接更简洁且不易出错。
内容的提问来源于stack exchange,提问作者aliyoung92
相关产品推荐
相关产品推荐

