我要浏览目录中的所有文件夹:
directory\
folderA\
a.cpp
folderB\
b.cpp
folderC\
c.cpp
folderD\
d.cpp
文件夹的名称都是已知的。
具体地说,我试图计算a.cpp
、b.cpp
、c.pp
和{folderA
并读取a.cpp
,计算行数,然后返回目录,进入folderB
,读取b.cpp
,计数行等
这就是我到现在为止所拥有的
^{2}$但我是Python新手,不知道我的方法是否合适以及如何继续。任何示例代码显示将不胜感激!在
另外,with open
是否像所有这些读取操作一样处理文件的打开/关闭,还是需要更多的处理?在
正如曼格拉诺所说,手术室步行()
您可以生成文件夹列表。在
您可以生成文件路径列表。在
^{pr2}$使用python3的
os.walk()
遍历给定路径的所有子目录和文件,打开每个文件并执行逻辑。您可以使用“for”循环来遍历它,从而大大简化代码。在https://docs.python.org/2/library/os.html#os.walk
我会这样做:
输出:
^{pr2}$关于
with
问题,您不需要关闭文件或进行任何其他检查。你应该像现在这样安全。在但是,您可以检查
full_path
是否存在,因为有人(您)可能会错误地从您的电脑中删除文件夹(来自list_of_folders
的文件夹)您可以通过
os.path.isdir
来完成此操作,如果文件存在,它将返回True
:os.path.isdir(full_path)
附言:我用的是python3。在
相关问题 更多 >
编程相关推荐