加载多个.mat光谱文件到Python时遇KeyError: 'fib4_spec'问题求助
解决KeyError: 'fib4_spec'问题
问题排查与处理步骤
- 先确认每个.mat文件的真实变量列表:在加载
mat_data后添加代码,打印排除元数据后的有效变量,避免因拼写差异、部分文件缺失变量导致报错:print(f"当前处理文件:{mat_file}") print(f"可用变量:{[k for k in mat_data.keys() if not k.startswith('__')]}") - 若部分文件确实缺失目标变量,添加跳过逻辑防止程序崩溃;若变量名存在但键名不符,直接替换为打印出的真实键名即可。
修改后的可运行代码
import os import matplotlib.pyplot as plt from scipy.io import loadmat %matplotlib inline %matplotlib widget # Directory containing the .mat files mat_files_dir = '/Users/xxxxx/Desktop/Tau Ceti/' # List all .mat files in the directory mat_files = [file for file in os.listdir(mat_files_dir) if file.endswith('.mat')] # Iterate through each .mat file for mat_file in mat_files: mat_data = loadmat(os.path.join(mat_files_dir, mat_file)) # 打印当前文件的有效变量(排除loadmat自带的元数据键) print(f"当前处理文件:{mat_file}") valid_vars = [k for k in mat_data.keys() if not k.startswith('__')] print(f"可用变量:{valid_vars}") # 检查目标变量是否存在 required_vars = ['fib4_spec', 'fib4_spec_wave'] if not all(var in mat_data for var in required_vars): print("缺少所需变量,跳过该文件\n") continue # Access the relevant variables spectrum_amplitude = mat_data['fib4_spec'] spectrum_wave = mat_data['fib4_spec_wave'] # Get the number of absorption lines (rows) num_lines = spectrum_amplitude.shape[0] # Create a single plot with subplots plt.figure(figsize=(12, 6)) for line_index in range(num_lines): line_amplitude = spectrum_amplitude[line_index] line_frequency = spectrum_wave[line_index] plt.plot(line_frequency, line_amplitude, label=f'Line {line_index+1}') plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.title('Tau Ceti - ' + os.path.splitext(mat_file)[0]) plt.legend() plt.show() print("文件处理完成\n")
额外情况处理
如果打印的变量列表中没有fib4_spec,但你确认Matlab文件内存在该变量,大概率是变量嵌套在结构体中。此时需要先访问结构体变量再索引字段,示例:
# 假设结构体变量名为'spec_struct' struct_data = mat_data['spec_struct'][0, 0] spectrum_amplitude = struct_data['fib4_spec'] spectrum_wave = struct_data['fib4_spec_wave']
内容的提问来源于stack exchange,提问作者AlbPet
相关产品推荐
相关产品推荐

