Python 脚本:读取文件夹中所有 txt 文件并提取每个文件中的峰值坐标
以下是用 Python 编写的程序,可以读取文件夹中所有的 txt 文件,并将每个 txt 文件中的峰值坐标以 Excel 表格输出:
import os
import pandas as pd
# 定义文件夹路径
folder_path = '文件夹路径'
# 读取文件夹中的 txt 文件
txt_files = [file for file in os.listdir(folder_path) if file.endswith('.txt')]
# 创建空的 DataFrame
data = pd.DataFrame(columns=['File', 'x_max', 'y_max'])
# 逐个读取 txt 文件
for file in txt_files:
file_path = os.path.join(folder_path, file)
# 从 txt 文件中读取数据
df = pd.read_csv(file_path, delimiter='\t', skiprows=1, names=['x', 'y'])
# 找到最大值的索引
max_index = df['y'].idxmax()
# 提取最大值和对应的 x 值
max_y = df.iloc[max_index]['y']
max_x = df.iloc[max_index]['x']
# 将最大值和对应 x 值添加到 DataFrame 中
data = data.append({'File': file, 'x_max': max_x, 'y_max': max_y}, ignore_index=True)
# 将数据保存到 Excel 表格
output_path = '输出文件路径'
data.to_excel(output_path, index=False)
请将代码中的 '文件夹路径' 替换为您要读取 txt 文件的实际文件夹路径,并将 '输出文件路径' 替换为您希望保存 Excel 文件的路径。运行程序后,将会在指定路径下生成一个包含每个文件中最大值和对应 x 值,并标明文件名的 Excel 表格。
原文地址: https://www.cveoy.top/t/topic/bczv 著作权归作者所有。请勿转载和采集!