How to List Files and Folders in a Directory using Python
Listing files and folders in a directory is a common task in Python programming. In this tutorial, we will explore different methods to accomplish this.
Using the os.listdir() Method
The built-in os
module in Python provides the listdir()
method, which can be used to retrieve a list of files and folders in a given directory. Here’s an example:
1 | import os |
In the above code, we import the os
module and set the dirname
variable to the desired directory path. Then, we use the os.listdir()
method to fetch a list of all files and folders present in the specified directory. Finally, we print the list of files and folders.
Obtaining the Full Path of Files
If you need to obtain the full path of each file in the directory, you can use the os.path.join()
method to combine the directory path with the filename. Here’s an example:
1 | import os |
In the above code, we utilize the os.path.join()
method to join the directory path (dirname
) with each filename in the files
list. We use the map()
function to apply this operation to every element in the files
list, and then convert it to a list using the list()
function. Finally, we print the list of full paths.
Separating Files and Folders
To list only the files or directories in a given directory, you can use the os.path.isfile()
and os.path.isdir()
methods. Here’s an example:
1 | import os |
In the above code, we create separate lists for directories (dirs
) and files (files
). We iterate through each full path in the fullpaths
list and use the os.path.isdir()
and os.path.isfile()
methods to determine whether each entry is a directory or a file. Depending on the result, we add the entry to the respective list. Finally, we print the lists of directories and files.
Remember to change the dirname
variable to the desired directory path in the above code snippets.
Conclusion
In this tutorial, you learned different methods to list files and folders in a directory using Python. These techniques allow you to manipulate and work with the file system in your Python programs efficiently.
tags: [“Python”, “file manipulation”, “directory listing”]