As samples in your auto-response, os.walk
is the natural multiplatform way to iterate recursively through the directory tree. As of Python 3.5 it uses internally os.scandir()
instead of os.listdir()
which significantly improves the execution time. Just to complete a bit and show how we could look for files that meet a certain pattern:
Since by definition we are only going to have a file with the same name (including the extension) within the same directory, instead of nesting a second for
, a conditional can be used with in
( membership testing ) which is more efficient.
If we do not know the number of files with that name present in our directory tree we can use a list to store each of the routes, we can use lists by compression if we want:
import os
target = "programa.exe"
initial_dir = 'C:\'
path_list = [os.path.join(root, target) for root, _, files in os.walk(initial_dir)
if target in files]
print(path_list)
If we know in advance that there is only one file with that name,
it is important to break the cycle to prevent the search from continuing
recursive unnecessarily once the file is found (which can save resources and significant time). If there are several files, the first one will be returned.
import os
target = "programa.exe"
initial_dir = 'C:\'
path = ''
for root, _, files in os.walk(initial_dir):
if target in files:
path = os.path.join(root, target)
break
print(path)
If we want to find the files with a given name but with any extension (or we do not know the extension) we can use the module fnmatch
(module that uses glob ) to enable the use of wildcards :
import os
import fnmatch
target = "programa.*"
initial_dir = 'C:\'
path_list = [os.path.join(root, file) for root, _, files in os.walk(initial_dir)
for file in fnmatch.filter(files, target)]
print(path_list)
We can create other patterns that allow us to search all the files with a certain extension, whose name starts or ends with a certain substring, etc. In case of wanting to look for more complex patterns we can resort to regular expressions as shown in point 6 of Mariano's answer to this related question:
How to list all files in a folder using Python?