问题描述
我正在使用os.walk在目录 foo中运行。我想处理.dat文件,但如何检查目录名称,而只处理特定目录?
I'm using os.walk to run through directory "foo". I want to process .dat files but how to check for a directory name and only process the specific directory?
If dir = bar然后处理files.dat。不处理 notbar。我可能错过了一些简单的东西
If dir="bar" then process files.dat. Do not process "notbar". I'm probably missing something simple
C:\data\foo
- notbar
-123
-file1.dat
-456
-file2.dat
-file3.dat
- bar
-123
-file1.dat
-456
-file2.dat
-file3.dat
这将找到所有.dat文件....
this finds all .dat files....
for (root, dirnames, filenames) in os.walk(base_path):
print('Found directory: {0}'.format(root))
for filename in filenames:
if filename.endswith(".dat"):
print(filename)
推荐答案
glob
真的很好。它将返回所有与特定模式匹配的文件。
glob
is really good for this. It returns all the files that match a certain pattern.
有一个,但最有用的是:
There is a reference for the patterns, but the most useful are:
-
*
匹配除路径斜杠外的所有内容(对于Windows,为\
,对于Mac / linux为/
) -
**
匹配零个或多个目录
*
matches everything except path slashes (\
for windows,/
for mac / linux)**
matches zero or more directories
在您的示例中,您要查找 .dat
( *。dat
)文件在任何子目录( * 基本路径
base_path
中的子目录( bar
)的code>。要获得这些文件,我们可以从glob导入glob
文件名= glob(base_path + \\来
In your example, you want to find the .dat
(*.dat
) files in any sub-directory (*
) of a sub-directory (bar
) inside a base path base_path
. To get these files we can write
from glob import glob
filenames = glob(base_path + "\\bar\\*\\*.dat")
最好使用 os.path.join
用于跨平台:
from glob import glob
filenames = glob(os.path.join(base_path, "bar", "*", "*.dat"))
查看结果
如果不需要 bar
ily是base_path的直接子目录,但嵌套得更深,可以使用 **
:
If bar
is not necessarily the immediate sub-directory of base_path, but nested further down, you could use **
:
from glob import glob
filenames = glob(os.path.join(base_path, "**", "bar", "*", "*.dat"))
最后,glob不一定会以任何顺序返回文件。要按字母顺序获取它们,请使用 sorted(filenames)
。要按照修改后的顺序使用它们,请按照sorted(filenames,key = os.path.getmtime) / how-do-you-get-a-directory-listing-sorting-by-creation-date-in-python>此答案。
Finally, glob will not necessarily return the files in any order. To get them in alphabetical order use sorted(filenames)
. To get them in modified order use sorted(filenames, key=os.path.getmtime)
as per this answer.
这篇关于使用python os.walk如何检查目录名称并仅在特定目录中(递归)处理那些文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!