python os.walk如何还原所有路径名_使用python os.walk如何检查目录名称并仅在特定目录中(递归)处理那些文件?...

这篇博客介绍了如何使用Python的glob模块来遍历指定目录'foo',并只处理名为'bar'子目录下的.dat文件。通过提供特定的glob模式,可以忽略其他非'bar'目录的文件。示例代码展示了如何在多级目录结构中查找匹配的.dat文件,并提供了按名称或修改时间排序的方法。
摘要由CSDN通过智能技术生成

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" 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

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 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:

* matches everything except path slashes (\ for windows, / for mac / linux)

** matches zero or more directories

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")

It is better to use os.path.join for cross-platform:

from glob import glob

filenames = glob(os.path.join(base_path, "bar", "*", "*.dat"))

Check out the results here

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"))

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值