遍历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
所有文件夹的名称都是已知的.
具体来说,我试图计算a.cpp
,b.cpp
,c.pp
和d.cpp
每个源文件上的代码行数.因此,进入folderA
并读取a.cpp
,对行进行计数,然后返回目录,进入folderB
,读取b.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. 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.
这是我到目前为止的想法,
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()
但是我是Python的新手,不知道我的方法是否合适以及如何进行.显示的任何示例代码将不胜感激!
but I am new to Python and have no idea if my approach is appropriate and how to proceed. Any example code shown will be appreciated!
此外,with open
是否按所有读取操作处理文件打开/关闭,还是需要更多处理?
Also, does the with open
handles the file opening/closing as it should for all those reads or more handling is required?
推荐答案
我会这样:
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
问题,您不需要关闭文件或进行任何其他检查.您应该现在就安全了.
Regarding the with
question, you don't need to close the file or make any other checks. You should be safe as it is now.
您可能,但是,请检查full_path
是否存在,因为有人(您)可能会错误地从PC删除文件夹(list_of_folders
的文件夹)
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
)
您可以通过os.path.isdir
执行此操作,如果文件存在,则返回True
:
You can do this by os.path.isdir
which returns True
if the file exists:
os.path.isdir(full_path)
PS:我使用的是Python3.
PS: I used Python 3.
这篇关于遍历Python中的所有文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!