在Python中浏览所有文件夹

2024-09-30 07:21:13 发布

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

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

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

文件夹的名称都是已知的。 具体地说,我试图计算a.cppb.cppc.pp和{}源文件上的代码行数。所以,进入folderA并读取a.cpp,计算行数,然后返回目录,进入folderB,读取b.cpp,计数行等

这就是我到现在为止所拥有的

^{2}$

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

另外,with open是否像所有这些读取操作一样处理文件的打开/关闭,还是需要更多的处理?在


Tags: 方法代码目录文件夹名称cppdirectorypp
3条回答

正如曼格拉诺所说,手术室步行()

您可以生成文件夹列表。在

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

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

^{pr2}$

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

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

我会这样做:

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)

输出:

^{pr2}$

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

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

您可以通过os.path.isdir来完成此操作,如果文件存在,它将返回True

os.path.isdir(full_path)

附言:我用的是python3。在

相关问题 更多 >

    热门问题