How To List Files In A Directory Python

Python is an incredibly versatile programming language, and one of its many useful features is the ability to work
with files and directories. In this blog post, we will learn how to list all the files in a directory using
Python.

Using the os module

The built-in os module provides an easy way to work with files and directories. To list the files
in a directory, we can use the os.listdir() function. Here’s a simple example:

    import os

    directory = '/path/to/your/directory'

    files_in_directory = os.listdir(directory)

    print(files_in_directory)
    

This will output a list containing the names of all files and directories inside the given directory. Note that
the os.listdir() function returns the file names, not their full paths. If you need the full
paths, you can use the os.path.join() function like this:

    import os

    directory = '/path/to/your/directory'

    files_in_directory = [os.path.join(directory, f) for f in os.listdir(directory)]

    print(files_in_directory)
    

Filtering out directories

If you only want to list files and exclude directories, you can use the os.path.isfile() function
to filter out the directories:

    import os

    directory = '/path/to/your/directory'

    files_in_directory = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]

    print(files_in_directory)
    

Using the glob module

An alternative to the os module for listing files in a directory is the glob
module, which allows you to use Unix shell-style wildcards to specify the file patterns. Here’s an example:

    import glob

    directory = '/path/to/your/directory'

    files_in_directory = glob.glob(directory + '/*')

    print(files_in_directory)
    

To only list files and exclude directories, you can use the glob.glob() function with the
os.path.isfile() function:

    import glob
    import os

    directory = '/path/to/your/directory'

    files_in_directory = [f for f in glob.glob(directory + '/*') if os.path.isfile(f)]

    print(files_in_directory)
    

Conclusion

In this blog post, we have learned how to list all files in a directory using Python’s built-in os
and glob modules. Whether you need a simple list of file names or a list of full file paths
without directories, Python provides easy-to-use functions to get the job done. Happy coding!