Python加载子文件夹CSV至对应命名列表/数组报错及解决方法
Python ImportCSVs函数报错:TypeError: 'WindowsPath' object is not iterable 问题排查与修复
问题描述
编写的导入CSV文件的Python函数如下:
def ImportCSVs(chatty = False): directory = os.path.join("c:\\", "data") files = pathlib.Path(directory) for file in files.iterdir(): if file.is_file(): filename, fileextention = os.path.splitext(file.name) if str(fileextention) == ".csv": f = open(file, 'r') if "Matrix" in str(pathlib.Path(filename).stem): if chatty == True: print("Loading Array:" + filename) filename.stem = list(csv.reader(file, delimiter=",")) else: if chatty == True: print("Loading List:" + filename) filename.stem = list(csv.reader(file, delimiter=",")) file.close() else: if chatty == True: print("Not Loaded:" + file)
运行时出现报错:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 16, in ImportCSVs TypeError: 'WindowsPath' object is not iterable
错误原因分析
- 核心报错原因:
csv.reader(file)中传入的file是pathlib.Path对象,而csv.reader需要接收可迭代的文件句柄(打开的文件对象),Path对象不具备可迭代性,因此抛出该错误。 - 文件句柄使用错误:已经用
f = open(file, 'r')获取了文件句柄,但后续没有使用f,反而用了Path对象file去读取,同时最后调用file.close()也是错误的,应该关闭的是f。 - 文件名处理逻辑错误:
filename是os.path.splitext得到的字符串,却试图访问它的stem属性(只有Path对象有这个属性),并且试图给该属性赋值,这完全不符合逻辑——这里应该是要把CSV数据存入变量,而不是修改文件名。 - 冗余代码:
str(pathlib.Path(filename).stem)完全多余,filename已经是去掉后缀的文件名,直接判断"Matrix" in filename即可。
修复后的代码
以下是修正后的函数,同时优化了逻辑,添加了返回值存储读取到的数据:
import os import csv import pathlib def ImportCSVs(chatty = False): directory = os.path.join("c:\\", "data") data_store = {} # 用来存储读取到的CSV数据,键是文件名 files = pathlib.Path(directory) for file in files.iterdir(): if file.is_file(): filename, fileextention = os.path.splitext(file.name) if fileextention == ".csv": # 无需转成字符串,直接比较 # 使用with语句自动管理文件,无需手动close with open(file, 'r', newline='') as f: if "Matrix" in filename: if chatty: print(f"Loading Array: {filename}") csv_data = list(csv.reader(f, delimiter=",")) data_store[filename] = csv_data else: if chatty: print(f"Loading List: {filename}") csv_data = list(csv.reader(f, delimiter=",")) data_store[filename] = csv_data else: if chatty: print(f"Not Loaded: {file}") return data_store
关键修复点
- 使用
with open(...) as f语句,自动处理文件的打开和关闭,避免手动关闭的错误。 - 将
csv.reader(file)改为csv.reader(f),传入正确的文件句柄。 - 新增
data_store字典,用来存储读取到的CSV数据,避免之前试图给文件名属性赋值的错误逻辑。 - 简化文件名判断逻辑,直接用
"Matrix" in filename。 - 优化打印语句,使用f-string更简洁。
内容的提问来源于stack exchange,提问作者Geoff Gill
相关产品推荐
相关产品推荐

