Python 3.6 glob include hidden files and folders

久未见 提交于 2019-12-23 09:37:23

问题


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)

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


回答1:


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

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)



回答2:


From https://docs.python.org/3/library/glob.html

If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

import glob

glob.glob('*.gif') # ['card.gif']

glob.glob('.c*') # ['.card.gif']

From what I see it requires two separate globs to get both hidden and not hidden ones, for example using https://stackoverflow.com/a/4829130/4130619 .



来源:https://stackoverflow.com/questions/49047402/python-3-6-glob-include-hidden-files-and-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!