Python使用split处理CSV文件时出现List index out of range错误
问题:CSV文件按分号分割时触发IndexError错误
我有一些来自其他程序、无法编辑的CSV文件,想通过split(";")分割内容,操作步骤是:
- 打开CSV文件
- 用
readlines()读取内容 - 调用
split(";")分割每行
但访问分割后的列表元素da_split[1]时触发IndexError: list index out of range错误,原因是首行内容分割后只返回1个元素。
代码实现
def get_data_csv(self): data = [] f = open("./filename.csv", 'r') data = f.readlines() print('Printout before splitting:') print(data) data1 = data for da in data1: da_split = [] da_split = da.split(";") print("Splitted: ") print(da_split) self.list_date.append(da_split[0]) self.list_tempAS.append(self.changeStrtoFloat(da_split[1]))
程序输出
Program Start Printout before splitting: ['Vorbereitung\n', 'Datum;Uhrzeit;Phase;Screen;Key;Interruptions;Temperatur AS;Temperatur SS;Gewichtswerte AS;Gewichtswerte SS;Info/Comment;\n', 'Nov 18;12:59:06;;;;;;;5613.74g;;;\n', 'Nov 18;12:59:01;;;;;;;5630.78g;;;\n', 'Nov 18;12:59:00;;;;;;;;5657.81g;;\n', 'Nov [...] Splitted: ['Vorbereitung\n'] Traceback (most recent call last): File "C:\Users\sp7820\PycharmProjects\graphLogger\main.py", line 99, in <module> main() File "C:\Users\sp7820\PycharmProjects\graphLogger\main.py", line 96, in main x.get_data_csv() File "C:\Users\sp7820\PycharmProjects\graphLogger\main.py", line 44, in get_data_csv self.list_tempAS.append(self.changeStrtoFloat(da_split[1])) IndexError: list index out of range Process finished with exit code 1
我试过用str()方法处理,但没有效果。
解决方案
1. 直接跳过不符合格式的首行
从输出能看到首行是Vorbereitung\n,没有分号,完全不需要处理,直接从第2行开始遍历:
def get_data_csv(self): data = [] with open("./filename.csv", 'r') as f: # 用with自动关闭文件,更安全 data = f.readlines() print('Printout before splitting:') print(data) # 从索引1开始,跳过首行 for da in data[1:]: da_split = da.strip().split(";") # strip去掉换行符,避免末尾的\n干扰 print("Splitted: ") print(da_split) # 注意:标题行的Temperatur AS是第7个字段(索引6),不是索引1 self.list_date.append(da_split[0]) # 处理温度值,先去掉末尾的g,再转float temp_as_str = da_split[6].strip('g') if temp_as_str: # 避免空字符串转float报错 self.list_tempAS.append(float(temp_as_str))
2. 增加长度判断,兼容异常行
如果不确定还有没有其他异常行,可以先判断分割后的列表长度,再访问元素:
def get_data_csv(self): data = [] with open("./filename.csv", 'r') as f: data = f.readlines() print('Printout before splitting:') print(data) for da in data: da_split = da.strip().split(";") print("Splitted: ") print(da_split) # 只有当列表长度足够时才处理 if len(da_split) >= 7: # 因为Temperatur AS在索引6,需要至少7个元素 self.list_date.append(da_split[0]) temp_as_str = da_split[6].strip('g') if temp_as_str: self.list_tempAS.append(float(temp_as_str))
3. 用Python内置csv模块(推荐)
手动split处理CSV很容易踩坑(比如换行符、引号包裹的字段、空字段),用标准库csv模块更稳定,它会自动处理这些细节:
import csv def get_data_csv(self): # with语句自动管理文件关闭 with open("./filename.csv", 'r', newline='', encoding='utf-8') as f: # 指定分隔符为; reader = csv.reader(f, delimiter=';') next(reader) # 跳过首行的Vorbereitung next(reader) # 跳过标题行(如果不需要标题的话) for row in reader: print("Row: ", row) self.list_date.append(row[0]) # 处理Temperatur AS字段,去掉g后转float temp_as_str = row[6].strip('g') if temp_as_str: self.list_tempAS.append(float(temp_as_str))
内容的提问来源于stack exchange,提问作者gamerInCellar
相关产品推荐
相关产品推荐

