Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There A Way To glob() Only Files?

I know that glob can look for all files or only all directories inside a folder :

echo "All files:\n"; $all = glob("/*"); var_dump($all);  echo "Only directories\n"; $dirs = glob("/*", GLOB_ONLYDIR); var_dump($dirs); 

But I didn't found something to find only files in a single line efficiently.

$files = array_diff(glob("/*"), glob("/*", GLOB_ONLYDIR)); 

Works well but reads directory twice (even if there are some optimizations that make the second browsing quicker).

like image 389
Alain Tiemblo Avatar asked Dec 29 '12 17:12

Alain Tiemblo


People also ask

How do I get all my glob files?

To use Glob() to find files recursively, you need Python 3.5+. The glob module supports the "**" directive(which is parsed only if you pass recursive flag) which tells python to look recursively in the directories.

How do I get a list of files in Python?

Use os.listdir() function The os. listdir('path') function returns a list containing the names of the files and directories present in the directory given by the path .


1 Answers

I finally found a solution :

echo "Only files\n"; $files = array_filter(glob("/*"), 'is_file'); var_dump($files); 

But take care, array_filter will preserve numeric keys : use array_values if you need to reindex the array.

like image 137
Alain Tiemblo Avatar answered Sep 28 '22 19:09

Alain Tiemblo