The easiest way to get the equivalent of "find." in python?

What is the easiest way to get a complete recursive list of files inside a folder using python? I know about os.walk() , but it seems unnecessarily easy to get an unfiltered list of all files. Is this really the only option?

+6
source share
5 answers

Nothing prevents you from creating your own function:

 import os def listfiles(folder): for root, folders, files in os.walk(folder): for filename in folders + files: yield os.path.join(root, filename) 

You can use it like this:

 for filename in listfiles('/etc/'): print filename 
+11
source

os.walk() not overflowing by any means. It can generate a list of files and directories in jiffy:

 files = [os.path.join(dirpath, filename) for (dirpath, dirs, files) in os.walk('.') for filename in (dirs + files)] 

You can turn this into a generator to process only one path at a time and safely in memory.

+4
source

Either this, either manually recursively with isdir() / isfile() and listdir() or you can use subprocess.check_output() and call find . . Bascially os.walk() is the highest level, a slightly lower level is a semi-manual solution based on listdir() , and if you want the same find . result find . would give you for some reason, you can make a system call using subprocess .

+1
source

You can also use the find program from Python with sh

 import sh text_files = sh.find(".", "-iname", "*.txt") 
+1
source
 import os path = "path/to/your/dir" for (path, dirs, files) in os.walk(path): print files 

Is this redundant, or am I missing something?

0
source

Source: https://habr.com/ru/post/925393/


All Articles