【发布时间】:2020-04-15 04:39:38
【问题描述】:
使用pathlib.Path().glob(),我们如何遍历一个目录,每次迭代读入2个文件?
假设我的目录C:\Users\server\Desktop\Dataset 如下所示:
P1_mean_fle.csv
P2_mean_fle.csv
P3_mean_fle.csv
P1_std_dev_fle.csv
P2_std_dev_fle.csv
P3_std_dev_fle.csv
如果我想在 Pi 的每次迭代中只读取 1 个文件,我的代码将如下所示:
from pathlib import Path
import pandas as pd
file_path = r'C:\Users\server\Desktop\Dataset'
param_file = 'P*' + '_mean_fle.csv'
for i, fle in enumerate(Path(file_path).glob(param_file)):
mean_fle = pd.read_csv(fle).values
results = tuning(mean_fle) #tuning is some function which takes in the file mean
#and does something with this file
现在,我如何在 Pi 的每次迭代中读取 2 个文件?下面的代码不太有效,因为param_file 只能分配一种文件名类型。如果有使用pathlib 的方法,将不胜感激。
from pathlib import Path
import pandas as pd
param_file = 'P*' + '_mean_fle.csv'
param_file = 'P*' + '_std_dev_fle.csv' #this is wrong
for i, fle in enumerate(Path(file_path).glob(param_file)): #this is wrong inside the glob() part
mean_fle = pd.read_csv(fle).values
std_dev_fle = pd.read_csv(fle).values
results = tuning(mean_fle, std_dev_fle) #tuning is some function which takes in the two files mean
#and std_dev and does something with these 2 files
提前谢谢你。
【问题讨论】:
标签: python loops for-loop glob pathlib