简体   繁体   English

浏览Python中的所有文件夹

[英]Going through all folders in Python

I want to go through all folders inside a directory: 我想浏览目录内的所有文件夹:

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

The name of the folders are all known. 文件夹的名称都是已知的。 Specifically, I am trying to count the number of lines of code on each of the a.cpp , b.cpp , c.pp and d.cpp source files. 具体来说,我正在尝试计算a.cppb.cppc.ppd.cpp源文件上的代码行数。 So, go inside folderA and read a.cpp , count lines and then go back to directory, go inside folderB , read b.cpp , count lines etc. 因此,进入folderA并读取a.cpp ,计算行数,然后返回目录,进入folderB ,读取b.cpp ,计数行等。

This is what I have up until now, 这是我到目前为止所拥有的,

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()

but I am new to Python and have no idea if my approach is appropriate and how to proceed. 但是我是Python的新手,不知道我的方法是否合适以及如何进行。 Any example code shown will be appreciated! 显示的任何示例代码将不胜感激!

Also, does the with open handles the file opening/closing as it should for all those reads or more handling is required? 另外, with open是否可以像所有这些读取一样处理文件打开/关闭,还是需要更多处理?

I would do it like this: 我会这样做:

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)

Output: 输出:

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

Regarding the with question, you don't need to close the file or make any other checks. 关于with问题,您不需要关闭文件或进行任何其他检查。 You should be safe as it is now. 您现在应该很安全。

You may , however, check if the full_path exists as somebody (you) could mistakenly delete a folder from your PC (a folder from list_of_folders ) 但是, 您可能会检查full_path存在,因为有人(您)可能会错误地从PC删除文件夹( list_of_folders的文件夹)

You can do this by os.path.isdir which returns True if the file exists: 您可以通过os.path.isdir来执行此操作,如果文件存在,则返回True

os.path.isdir(full_path)

PS: I used Python 3. PS:我使用了Python 3。

Use Python 3's os.walk() to traverse all subdirectories and files of a given path, opening each file and do your logic. 使用Python 3的os.walk()遍历给定路径的所有子目录和文件,打开每个文件并执行逻辑。 You can use a 'for' loop to walk it, simplifying your code greatly. 您可以使用“ for”循环来遍历它,从而大大简化您的代码。

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

As manglano said, os.walk() 正如manglano所说,os.walk()

you can generate a list of folder. 您可以生成文件夹列表。

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

you can generate a list of file path. 您可以生成文件路径列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM