使用 os.walk 查找文件,然后连接从每个文件创建的各个数据帧:
import pandas as pd
import os
txtfolder = r'/home/bera/Desktop/textfiles/' #Change to your folder path
#Find the textfiles
textfiles = []
for root, folder, files in os.walk(txtfolder):
for file in files:
if file.endswith('.txt'):
fullname = os.path.join(root, file)
textfiles.append(fullname)
textfiles.sort() #Sort the filesnames
#Read each of them to a dataframe
for filenum, file in enumerate(textfiles, 1):
if filenum==1:
df = pd.read_csv(file, names=['value1','value2','value3','value4'], delim_whitespace=True)
df['Samplename']=os.path.basename(file)
else:
tempdf = pd.read_csv(file, names=['value1','value2','value3','value4'], delim_whitespace=True)
tempdf['Samplename']=os.path.basename(file)
df = pd.concat([df, tempdf], ignore_index=True)
df = df[['Samplename','value1','value2','value3','value4']] #Reorder columns
# Samplename value1 value2 value3 value4
# 0 1.txt 0.007812 0.000826 0.007812 -0.033145
# 1 1.txt 0.015625 0.000642 0.015625 -0.031452
# 2 1.txt 0.023437 -0.001057 0.023437 -0.037753
# 3 1.txt 0.031250 -0.000166 0.031250 -0.002330
# 4 1.txt 0.039062 0.002405 0.039062 0.042441
# 5 2.txt 0.007812 -0.004095 0.007812 -0.010042
# 6 2.txt 0.015625 0.002398 0.015625 0.033428