Python is a versatile programming language with vast capabilities, including file handling. In this blog post, we’ll cover how you can list all the files in a directory using Python. This can be especially useful when you want to perform a batch operation on multiple files, such as renaming or moving them.
Using the os module
Python has a built-in module called os which provides a simple way to interact with the file system. To get a list of all the files in a specific directory, we can use the os.listdir() function. This function returns a list containing the names of the files and directories in the specified path.
This code snippet above will print the names of all the files and directories in the specified path. Note that if you want to list the files in the current working directory, you can use the os.getcwd() function as the argument for the os.listdir() function:
Filtering out directories
You might only be interested in listing the files and not the directories. To achieve this, you can use the os.path.isfile() function to filter out directories from the list:
The code snippet above uses a list comprehension to filter out directories and only include files in the files_list.
Using the glob module
Another way to list all the files in a directory is by using the glob module. The glob.glob() function returns a list of file paths that matches a specified pattern. By using a wildcard character *, you can list all the files in a directory:
Keep in mind that the output will include the full path of the files instead of just their names. If you only need the file names, you can use the os.path.basename() function:
In this blog post, we’ve demonstrated how to list all the files in a directory using Python’s built-in os and glob modules. You can use either of these methods depending on your specific requirements and the format of the output you need.