【发布时间】:2019-04-05 20:42:11
【问题描述】:
我在一个包含 36 个不同文件夹的目录中。每个文件夹中都有一个 csv。我想将它们中的每一个附加在一起以在 python 中创建一个大数据框。
在 R 中,我会这样做:
cwd = getwd() #get current directory
fil = list.files() #get list of all files/folders in the directory
Bigdf = NULL #initialize empty df
for(i in fil){ #read through all folders in current directory
setwd(paste0(cwd,'/',i)) #navigate to i'th folder
fil2 = list.files() #get list of files in i'th folder
for(j in fil2){
a = read.csv(paste0(cwd,'/',i,'/',j)) #read in all csv's
Bigdf = rbind(Bigdf,a[,c(2,4:11)]) #append desired columns to data frame
}
setwd(cwd)
}
我将如何在 python 中做这样的事情?
我尝试实现How can I read the contents of all the files in a directory with pandas? 和How do I list all files of a directory?,但无济于事。我想我遗漏了一些明显的东西,希望有人能指出我正确的方向。
【问题讨论】:
-
您可能想看看模块
os(例如os.listdir)和csv。 -
就是这样,谢谢指导
标签: python r dataframe navigation