【问题标题】:Going through all folders in Python遍历 Python 中的所有文件夹
【发布时间】:2016-04-04 19:38:35
【问题描述】:

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

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

文件夹的名称都是已知的。 具体来说,我试图计算每个a.cpp、b.cpp、c.pp 和d.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 是否处理文件打开/关闭,因为它应该为所有这些读取或需要更多处理?

【问题讨论】:

    标签: python python-3.x file-handling


    【解决方案1】:

    我会这样做:

    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 是否存在,因为某人(您)可能会错误地从您的 PC 中删除一个文件夹(来自list_of_folders 的文件夹)

    您可以通过os.path.isdir 执行此操作,如果文件存在,则返回True:

    os.path.isdir(full_path)

    PS:我用的是 Python 3。

    【讨论】:

      【解决方案2】:

      使用 Python 3 的 os.walk() 遍历给定路径的所有子目录和文件,打开每个文件并执行您的逻辑。你可以使用'for'循环来遍历它,大大简化你的代码。

      https://docs.python.org/2/library/os.html#os.walk

      【讨论】:

        【解决方案3】:

        正如 manglano 所说,os.walk()

        您可以生成文件夹列表。

        [src for src,_,_ in os.walk(sourcedir)]
        

        您可以生成文件路径列表。

        [src+'/'+file for src,dir,files in os.walk(sourcedir) for file in files]
        

        【讨论】:

          猜你喜欢
          • 2014-04-24
          • 1970-01-01
          • 1970-01-01
          • 2022-10-24
          • 2020-08-09
          • 1970-01-01
          • 1970-01-01
          • 2021-11-26
          相关资源
          最近更新 更多