如何用Python循环批量处理傅里叶滤波数据并导出到对应文本文件
批量处理傅里叶滤波数据的解决方案
没问题,我来帮你搞定批量处理raw数据并保存滤波结果的需求!下面是完整的实现代码,我会逐部分解释关键逻辑:
import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.fftpack import rfft, irfft, fftfreq import os # 新增:用于文件路径管理和文件夹遍历 # 这里假设你已经有成熟的Filter函数实现,我写了一个基础版本供参考,你可以替换成自己的 def Filter(time, signal, lowcut, highcut, plot_flag, cutoff): n = len(time) dt = time[1] - time[0] freq = fftfreq(n, dt) f_signal = rfft(signal) # 保留指定频率区间的信号 mask = (freq >= lowcut) & (freq <= highcut) f_signal[~mask] = 0 filtered_signal = irfft(f_signal) # 按cutoff参数截断信号(和你原代码逻辑一致) if cutoff > 0: filtered_signal = filtered_signal[int(cutoff/dt):] # 可选绘图功能 if plot_flag: plt.figure() plt.plot(time, signal, label='Original') plt.plot(time[int(cutoff/dt):] if cutoff>0 else time, filtered_signal, label='Filtered') plt.legend() plt.show() return filtered_signal # ---------------------- 批量处理核心逻辑 ---------------------- # 动态获取脚本所在目录,避免硬编码路径的局限性 script_dir = os.path.dirname(os.path.abspath(__file__)) raw_data_dir = os.path.join(script_dir, 'Raw_data') filtered_data_dir = os.path.join(script_dir, 'Filtered_data') # 确保输出文件夹存在,不存在则自动创建 os.makedirs(filtered_data_dir, exist_ok=True) # 遍历原始数据文件夹中的目标文件 for filename in os.listdir(raw_data_dir): # 只处理符合命名规则的txt文件 if filename.startswith('rawtest_datafile') and filename.endswith('.txt'): raw_file_path = os.path.join(raw_data_dir, filename) try: # 读取数据(和你原代码逻辑一致) data = pd.read_csv(raw_file_path) time = np.linspace(0, 4017, 4018) signal = data.TG # 执行滤波计算 filtered_result = Filter(time, signal, 0.004, 0.0075, False, 0.04) / 10 # 生成对应输出文件名 output_filename = filename.replace('rawtest', 'filteredtest') output_file_path = os.path.join(filtered_data_dir, output_filename) # 保存滤波结果,这里用numpy保存一维数组,可自定义精度 np.savetxt(output_file_path, filtered_result, fmt='%.6f') print(f"✅ 已完成:{output_filename}") except Exception as e: print(f"❌ 处理{filename}出错:{str(e)}")
关键细节说明:
- 路径灵活性:用
os.path系列函数动态构建路径,就算你移动整个文件夹,代码也不用修改路径参数。 - 容错处理:
os.makedirs(..., exist_ok=True)确保输出文件夹存在,try-except捕获单个文件的处理错误,不会因为一个坏文件导致整个批量任务中断。 - 文件筛选:通过
startswith和endswith精准匹配你需要处理的文件,避免误处理其他无关txt。 - 命名对应:用
replace快速将rawtest替换为filteredtest,保证输入输出文件名一一对应。
可选调整项:
- 如果你的原始数据时间轴不是固定的
linspace(0,4017,4018),可以改成从文件中读取时间列,比如time = data['time'](需要你的txt文件包含time列)。 - 若需要保存带表头的结果,可以用pandas替代numpy保存:
pd.DataFrame(filtered_result, columns=['Filtered_TG']).to_csv(output_file_path, index=False)
内容的提问来源于stack exchange,提问作者Ruben
相关产品推荐
相关产品推荐

