Categories
Python Answers

How to find a file with Python?

Spread the love

Sometimes, we want to find a file with Python.

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

How to find a file with Python?

To find a file with 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)


print(find('data.xlsx', './'))

We defined the find function that calls os.walk with path.

In the function we loop through the files and directories returned from the iterator starting from the path‘s level and below.

And we check if the name is in the files array to check if the file with the given name is in the files array.

If that’s True, then we return the full path of the file with os.path.join.

Therefore, if the file is found, then we get something like './data.xlsx'. from print.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to find a file with Python?”

Leave a Reply

Your email address will not be published. Required fields are marked *