Python 3.6 glob包含隐藏的文件和文件夹 [英] Python 3.6 glob include hidden files and folders

查看:353
本文介绍了Python 3.6 glob包含隐藏的文件和文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试遍历与某个扩展名匹配的所有文件,包括隐藏文件夹中的文件.到目前为止,我还没有找到使用iglob做到这一点的方法. 这适用于除以点开头的所有文件夹之外的所有文件夹:

I try to loop over all files matching a certain extension, including those inside hidden folders. So far I haven't found a way to do this with iglob. This works for all folder except those starting with a dot:

import glob
for filename in glob.iglob('/path/**/*.ext', recursive=True):
    print(filename)

我试图将点添加为可选字符无济于事.我真的很想使用glob而不是驻留在os.walk

I have tried to add the dot as an optional character to no avail. I'd really like to use glob instead of residing to os.walk

推荐答案

我遇到了同样的问题,希望glob.glob具有一个可选参数来包含点文件.我希望能够在所有目录中包括所有点文件,包括以点开头的目录.使用glob.glob不可能做到这一点.但是我发现Python具有pathlib标准模块,该模块具有glob函数,该函数的操作方式有所不同,它将包含点文件.该函数的操作稍有不同,特别是它不返回字符串列表,而是返回路径对象.但是我使用了以下

I had this same issue and wished glob.glob had an optional parameter to include dot files. I wanted to be able to include ALL dot files in ALL directories including directories that start with dot. Its just not possible to do this with glob.glob. However I found that Python has pathlib standard module which has a glob function which operates differently, it will include dot files. The function operates a little differently, in particular it does not return a list of strings, but instead path objects. However I used the following

files=[]
file_refs = pathlib.Path(".").glob(pattern)
for file in file_refs:
    files.append(str(file))

我发现的另一个显着差异是以**结尾的全局模式.这在pathlib版本中不返回任何内容,但将返回glob.glob中的所有文件.为了获得相同的结果,我添加了一行以检查模式是否以**结尾,如果是,则在其后附加/*.

The other noticeable difference I found was a glob pattern ending with **. This returned nothing in the pathlib version but would return all the files in the glob.glob one. To get the same results I added a line to check if the pattern ended with ** and if so then append /* to it.

以下代码替代了您的示例,该示例包括以点开头的目录中的文件

The following code is a replacement for your example that include the files in directories starting with dot

import pathlib
for fileref in pathlib.Path('/path/').glob('**/*.ext'):
    filename = str(fileref)
    print(filename)

这篇关于Python 3.6 glob包含隐藏的文件和文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆