从子目录导航并附加csv

2024-04-16 23:24:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个目录里,有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?,但没有结果。我想我遗漏了一些明显的东西,希望有人能给我指出正确的方向。你知道吗


Tags: ofcsvthein文件夹readgetfiles