我想浏览目录中的所有文件夹:
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
是否会像所有这些读取操作那样处理文件打开/关闭或需要更多处理?
最佳答案
我会这样做:
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/