You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取带表头TXT文件提取数值列返回空列表如何解决

问题原因分析
  • 分隔符使用错误:你的文件是逗号分隔的CSV格式,原代码用split()按空白符分割,每行的三个值会被当成一个整体字符串,无法转换为float,所有行都会触发ValueError进入continue分支,所以最终列表为空。
  • 逻辑冗余问题:原代码中的remove([])逻辑完全不必要,正常情况下不会有空列表被追加到结果中,反而可能引发额外异常。
  • 路径风险:路径拼接时直接使用单反斜杠\可能会触发转义字符问题,容易出现路径找不到的报错。
  • 多余代码:with上下文管理器会自动关闭文件,末尾的f_de.close()属于无效冗余代码。
修复后的代码
import os

lc_empty_cp = []
dc_empty_cp = []
# 用os.path.join拼接路径,避免转义问题
file_path = os.path.join(path_cp, f'DNV_E{file_type}')

with open(file_path, 'r', encoding='utf-8') as f_de:
    # 先读取表头,自动定位_LCC_和_DCC_的列索引
    header = [col.strip() for col in f_de.readline().strip().split(',')]
    index_lc = header.index('_LCC_')
    index_dc = header.index('_DCC_')
    
    # 遍历剩余数据行
    for line_de in f_de:
        line_de = line_de.strip()
        if not line_de:
            continue
        # 按逗号分割,去除每个字段前后的空白
        parts = [p.strip() for p in line_de.split(',')]
        # 提取对应列转换为浮点型
        lc_empty_cp.append(float(parts[index_lc]))
        dc_empty_cp.append(float(parts[index_dc]))

# 如需匹配你给出的预期输出格式,直接合并两个列表即可
merged_result = [f"{lc:.3e} {dc:.3e}" for lc, dc in zip(lc_empty_cp, dc_empty_cp)]
print("[" + "\n\t".join(merged_result) + "]")

内容的提问来源于stack exchange,提问作者user17033609

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:27:02