如何用Python从CSV文件中提取指定行列的数据?
CSV指定行列数据提取方案
常见错误原因
list index out of range:大概率是这几个问题:- Python是从0开始索引的,你写的row=2、column=3对应实际第3行第4列,很容易超出实际数据范围
- CSV文件的列分隔符不是默认的逗号(比如用了分号),导致解析后列数不对
- 指定的行号超过了文件实际的行数
- 打印纯文本:说明你只是直接读取了文件内容,没有用CSV解析工具拆分数据结构
基础实现代码(匹配你的需求)
import csv # 注意:Python索引从0开始,原需求的row=2对应这里的1,column=3对应这里的2 target_col = 2 target_row = 1 expected_value = "john doe" with open("example.csv", "r", newline="", encoding="utf-8") as f: # 读取所有行到列表 csv_rows = list(csv.reader(f)) # 先校验索引是否有效 if target_row < len(csv_rows) and target_col < len(csv_rows[target_row]): if csv_rows[target_row][target_col] == expected_value: print("true") else: print("false") else: print("指定的行或列超出文件范围")
灵活提取的函数封装
如果需要频繁切换行/列,可以封装成函数,方便复用:
import csv def get_csv_cell(file_path, row_idx, col_idx): with open(file_path, "r", newline="", encoding="utf-8") as f: csv_rows = list(csv.reader(f)) # 校验行索引 if row_idx < 0 or row_idx >= len(csv_rows): return None # 校验列索引 if col_idx < 0 or col_idx >= len(csv_rows[row_idx]): return None return csv_rows[row_idx][col_idx] # 使用示例:取第2行第3列(对应索引1和2) cell_content = get_csv_cell("example.csv", 1, 2) if cell_content == "john doe": print("true") else: print("false" if cell_content is not None else "索引越界")
额外注意事项
- 如果你的CSV用分号、制表符分隔,要给
csv.reader加delimiter参数,比如csv.reader(f, delimiter=";") - 若文件打开乱码,尝试修改
encoding参数为gbk或utf-8-sig - 如果CSV有表头,要注意表头行是第0行,数据行从第1行开始计数
内容的提问来源于stack exchange,提问作者Bio
相关产品推荐
相关产品推荐

