太过简单,仅用于记录,自己看吧
import os
folder_path = "D:/yanhua/PSO/PSO/Results/NP=20"# 文件夹路径
output_file = "C:/Users/hongkun/OneDrive/桌面/123.txt" # 输出文件路径
with open(output_file, "w") as f:
f.write("文件名\t行数\n") # 写入表头
for file_name in os.listdir(folder_path):
if file_name.endswith(".txt"):
file_path = os.path.join(folder_path, file_name)
with open(file_path, "r") as f:
lines = f.readlines()
if len(lines) >= 10:
with open(file_path, "w") as f:
f.writelines(lines[:10])
else:
with open(output_file, "a") as f:
f.write(f"{file_name}\t{len(lines)}\n")