Python:循环在python中打开多个文件夹和文件

Tin*_*y_Y 5 python jupyter-notebook

我是 Python 新手,目前从事数据分析工作。

我正在尝试循环打开多个文件夹并读取文件夹中的所有文件。前任。工作目录包含需要打开的 10 个文件夹,每个文件夹包含 10 个文件。

我用 .txt 文件打开每个文件夹的代码;

file_open = glob.glob("home/....../folder1/*.txt")
Run Code Online (Sandbox Code Playgroud)

我想打开文件夹 1 并读取所有文件,然后转到文件夹 2 并读取所有文件...直到文件夹 10 并读取所有文件。任何人都可以帮助我如何编写循环来打开文件夹,需要使用包含的库吗?

我有 R 的背景,例如,在 RI 中可以编写循环来打开文件夹和文件,使用下面的代码。

folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
    file_open <-dir(paste0("......./main/",folder_open[n]))

    for (k in 1 to length of (file_open){
        file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
        //Finally I can read all folders and files.
    }
}
Run Code Online (Sandbox Code Playgroud)

Gal*_*bra 5

这种递归方法将扫描给定目录中的所有目录,然后打印文件的名称txt。我诚挚地邀请您推动这一进程。

import os

def scan_folder(parent):
    # iterate over all the files in directory 'parent'
    for file_name in os.listdir(parent):
        if file_name.endswith(".txt"):
            # if it's a txt file, print its name (or do whatever you want)
            print(file_name)
        else:
            current_path = "".join((parent, "/", file_name))
            if os.path.isdir(current_path):
                # if we're checking a sub-directory, recursively call this method
                scan_folder(current_path)

scan_folder("/example/path")  # Insert parent direcotry's path
Run Code Online (Sandbox Code Playgroud)