Menu Close

How to find a file in Python?

Sometimes, we want to find a file in Python.

In this article, we’ll look at how to find a file in Python.

How to find a file in Python?

To find a file in Python, we can use the os.walk method.

For instance, we write

import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

to define the find function to find the file with name in the path.

In it, we call os.walk to loop through the files in path in all child directories of path.

And we check if name is in files.

If it is, we return the path of the file with name with

os.path.join(root, name)

Conclusion

To find a file in Python, we can use the os.walk method.

Posted in Python, Python Answers