我很好奇在结果列表中添加行是否就足够满足您的需要:
import pandas as pd
import csv
import glob
import os
# Use a list here rather than a dataframe
results=[]
filelist = glob.glob("C:\\Users\\ryans\\OneDrive\\Desktop\\test\\*.txt")
number_of_lines = 2
for filename in filelist:
with open(filename) as myfile:
head = [next(myfile) for x in range(2)]
results.append([filename, *head])
# You can build a dataframe from that list at the end if you desire
results_df = pd.DataFrame.from_records(results, columns=['filename', 'head_1', 'head_2'])