[英]Going through all folders in Python
我想浏览目录内的所有文件夹:
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
存在,因为有人(您)可能会错误地从PC删除文件夹( list_of_folders
的文件夹)
您可以通过os.path.isdir
来执行此操作,如果文件存在,则返回True
:
os.path.isdir(full_path)
PS:我使用了Python 3。
使用Python 3的os.walk()
遍历给定路径的所有子目录和文件,打开每个文件并执行逻辑。 您可以使用“ for”循环来遍历它,从而大大简化您的代码。
正如manglano所说,os.walk()
您可以生成文件夹列表。
[src for src,_,_ in os.walk(sourcedir)]
您可以生成文件路径列表。
[src+'/'+file for src,dir,files in os.walk(sourcedir) for file in files]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.