如何用Python动态跳过行读取满足列数/列名条件的CSV文件?
动态读取CSV文件:跳过前置行直到目标行
问题根源
你之前的代码逻辑错误:在未读取文件的情况下就尝试操作df,且FILE-START并非合法列名,导致代码无法运行。正确做法是先逐行扫描文件定位起始行,再执行读取。
实现方案
以下代码同时满足两个触发条件:找到包含6列的行,或匹配指定列名序列的行,从该行开始读取数据:
import pandas as pd filename = "File.csv" target_header = ["Col1", "col2", "col3", "col4", "col5", "col6"] start_idx = None # 逐行扫描文件,定位起始行 with open(filename, 'r', encoding='utf-8') as f: for line_num, line in enumerate(f): line_clean = line.strip() if not line_clean: continue # 跳过空行 columns = line_clean.split(',') # 检查两个触发条件 if len(columns) == 6 or columns == target_header: start_idx = line_num break # 执行读取 if start_idx is not None: # 根据是否是表头行设置header参数 header_param = 0 if columns == target_header else None df = pd.read_csv(filename, skiprows=start_idx, header=header_param) print(df) else: print("未找到符合条件的起始行")
代码解释
- 先打开文件逐行遍历,跳过空行后分割每行内容为列列表
- 同时校验两个条件:列数为6,或列名与
target_header完全匹配 - 找到起始行后,判断该行是否为表头:若是则用
header=0将其设为列名;若为数据行则用header=None - 通过
skiprows参数跳过起始行之前的所有内容,精准读取目标数据
针对示例文件的运行结果
代码会定位到第10行(索引从0开始)的Col1,col2,col3,col4,col5,col6,读取后输出:
Col1 col2 col3 col4 col5 col6 0 1 2 3 4 5 6 1 qw ers hh yj df ji
内容的提问来源于stack exchange,提问作者Keshav
相关产品推荐
相关产品推荐

