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

Python如何顺序读取多文件夹数据并处理光谱数据绘制二维彩图

问题解决方案

1 报错原因

os.listdir(path)仅返回目标路径下的文件/文件夹名称字符串,不包含父路径前缀。直接传入open()时,Python会默认从当前脚本的工作目录查找文件,而不是你传入的path目录,因此触发文件不存在报错。

2 修复后的代码(支持单个文件夹处理)

import os

angles_data = []
# 这里替换为你的目标文件夹路径
path = "你的文件夹绝对/相对路径"
f = sorted_alphanumeric(os.listdir(path))
print(f)

for file in f:
    # 拼接得到文件完整路径
    full_file_path = os.path.join(path, file)
    # 用with上下文管理器自动处理文件关闭,避免手动关文件的逻辑错误
    with open(full_file_path, 'r', encoding='utf-8') as token:
        linestoken = token.readlines()
    tokens_column_number = 1
    resulttoken2 = []
    for x in linestoken:
        resulttoken2.append(x.split()[tokens_column_number])
    # 删除表头行
    del resulttoken2[0]
    new_list = [float(i) for i in resulttoken2]
    angles_data.append(new_list)

print(angles_data)

注意:你原代码中token.close()写在了读取行的循环内部,第一次读取行就会关闭文件,后续行读取会报错,上述代码用with上下文管理器规避了这个问题。

3 扩展:自动遍历16个样本文件夹

如果你的所有Sample文件夹都放在同一个根目录下,可以用以下逻辑批量处理:

import os

root_path = "存放所有Sample文件夹的根目录路径"
all_samples_data = {}

# 遍历根目录下的所有Sample文件夹
for sample_dir in sorted_alphanumeric(os.listdir(root_path)):
    # 筛选名称符合Sample+数字格式的文件夹
    if not sample_dir.startswith("Sample"):
        continue
    sample_full_path = os.path.join(root_path, sample_dir)
    if not os.path.isdir(sample_full_path):
        continue
    
    angles_data = []
    # 处理单个样本文件夹内的所有光谱文件
    for file in sorted_alphanumeric(os.listdir(sample_full_path)):
        if not file.endswith(".txt"):
            continue
        full_file_path = os.path.join(sample_full_path, file)
        with open(full_file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        # 提取第二列数据,跳过表头
        col_data = [float(line.split()[1]) for line in lines[1:]]
        angles_data.append(col_data)
    # 存入字典,key为样本文件夹名
    all_samples_data[sample_dir] = angles_data

# 后续可以遍历all_samples_data计算反射系数、绘图

额外优化建议

  • 如果你的光谱文件格式统一,也可以用pandas的read_csv函数直接提取指定列,代码会更简洁:pd.read_csv(full_file_path, sep='\s+', usecols=[1], skiprows=[0]).values.flatten().tolist()
  • 计算反射系数时可以提前把光源、背景光谱单独提取出来,避免每次循环重复读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 08:45:03