python - 遍历Python中的所有文件夹

标签 python python-3.x file-handling

我想浏览目录中的所有文件夹:

directory\  
   folderA\
         a.cpp
   folderB\
         b.cpp
   folderC\
         c.cpp
   folderD\
         d.cpp

文件夹的名称都是已知的。 具体来说,我试图计算每个 a.cppb.cppc.ppd.cpp 源文件。因此,进入 folderA 并读取 a.cpp,计算行数,然后返回目录,进入 folderB 内部,读取 b .cpp,计算行数等

这就是我到目前为止所拥有的,

dir = directory_path
for folder_name in folder_list():
    dir = os.path.join(dir, folder_name)
    with open(dir) as file:
        source= file.read()
    c = source.count_lines()

但我是 Python 新手,不知道我的方法是否合适以及如何继续。任何显示的示例代码将不胜感激!

此外,with open 是否会像所有这些读取操作那样处理文件打开/关闭或需要更多处理?

最佳答案

我会这样做:

import glob
import os

path = 'C:/Users/me/Desktop/'  # give the path where all the folders are located
list_of_folders = ['test1', 'test2']  # give the program a list with all the folders you need
names = {}  # initialize a dict

for each_folder in list_of_folders:  # go through each file from a folder
    full_path = os.path.join(path, each_folder)  # join the path
    os.chdir(full_path)  # change directory to the desired path

    for each_file in glob.glob('*.cpp'):  # self-explanatory
        with open(each_file) as f:  # opens a file - no need to close it
            names[each_file] = sum(1 for line in f if line.strip())

    print(names)

输出:

{'file1.cpp': 2, 'file3.cpp': 2, 'file2.cpp': 2}
{'file1.cpp': 2, 'file3.cpp': 2, 'file2.cpp': 2}

关于with问题,您不需要关闭文件或进行任何其他检查。你应该像现在一样安全。

但是,您可以检查 full_path 是否存在的原因是某人(您)可能会错误地从您的电脑中删除文件夹(来自 list_of_folders 的文件夹)

您可以通过os.path.isdir来做到这一点返回 True如果文件存在:

os.path.isdir(full_path)

PS:我使用的是Python 3。

关于python - 遍历Python中的所有文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36411416/

相关文章:

python - 如何将 dict(zip(range(n), range(n))) 翻译成 Python 3?

c++ - 从文件中解压缩数据时出现段错误(使用 strtok() 和 strcpy() )?

python - 如何在基于其他数据帧的数据帧中创建联接?

python - 如果我使用 pip3 安装 AWS CLI,如何修复 "dyld: Library not loaded"?

python-3.x - 显示 IF 语句的函数与 IF 语句的工作方式不同

python-3.x - Python不等于0

c - Dev-C++ 文件处理

c++ - 如何在 C++ 中将 char 转换为 int? (文件处理)

python - 使用 python 查找 Excel 中的列中是否存在某个值

python - SciKitlearn ColumnTransformer TypeError : Cannot clone object. 你应该提供一个 scikit-learn estimator 的实例而不是一个类