import os import pandas as pd # 读取txt文件的最后一行,并将所有最后一行(并加入了被试编号)保存在excel表中 dir_path = 'F:\MyOperation_train_after2\statistical_results\statistical_curv' file_path = '' sub_name = '' last_lines_list = [] for i in range(1, 82): if i < 42: if i < 10: sub = 'FX100' + str(i) sub_name = 'FX100' + str(i) + '.lh.cluster-001.curv.txt' file_path = os.path.join(dir_path, sub_name) if os.path.exists(file_path): with open(file_path, 'r') as file: lines = file.readlines() last_lines = lines[-1:] # 获取最后1行数据 last_lines.insert(0, sub) last_lines_list.append(last_lines) else: print("*************************************************") print(file_path, "不存在") print("*************************************************") else: sub = 'FX10' + str(i) sub_name = 'FX10' + str(i) + '.lh.cluster-001.curv.txt' file_path = os.path.join(dir_path, sub_name) if os.path.exists(file_path): with open(file_path, 'r') as file: lines = file.readlines() last_lines = lines[-1:] # 获取最后1行数据 last_lines.insert(0, sub) last_lines_list.append(last_lines) else: print("*************************************************") print(file_path, "不存在") print("*************************************************") else: if (i - 41) < 10: sub = 'KG200' + str(i - 41) sub_name = 'KG200' + str(i - 41) + '.lh.cluster-001.curv.txt' file_path = os.path.join(dir_path, sub_name) if os.path.exists(file_path): with open(file_path, 'r') as file: lines = file.readlines() last_lines = lines[-1:] # 获取最后1行数据 last_lines.insert(0, sub) last_lines_list.append(last_lines) else: print("*************************************************") print(file_path, "不存在") print("*************************************************") else: sub = 'KG20' + str(i - 41) sub_name = 'KG20' + str(i - 41) + '.lh.cluster-001.curv.txt' file_path = os.path.join(dir_path, sub_name) if os.path.exists(file_path): with open(file_path, 'r') as file: lines = file.readlines() last_lines = lines[-1:] # 获取最后1行数据 last_lines.insert(0, sub) last_lines_list.append(last_lines) else: print("*************************************************") print(file_path, "不存在") print("*************************************************") for i in last_lines_list: print(i) # 创建DataFrame对象 df = pd.DataFrame(last_lines_list, columns=['Name', 'messages']) # 保存到Excel表中 # index=False 参数用于禁止保存索引列。 df.to_excel('curv_extract_value.xlsx', index=False)