Listing Files Using the os.listdir() Function
The os.listdir()
function is a powerful tool for retrieving a list of files and directories within a specified directory. In this section, we'll dive deeper into the usage and features of this function.
Basic Usage
To list the contents of a directory using os.listdir()
, you can simply pass the path to the directory as an argument:
import os
directory_path = '/home/user/documents'
file_list = os.listdir(directory_path)
for item in file_list:
print(item)
This will output a list of all the files and directories within the /home/user/documents
directory.
Handling Relative Paths
You can also use relative paths when calling os.listdir()
. For example, if you want to list the contents of the current working directory, you can simply pass an empty string or the .
character:
import os
current_dir = os.listdir('.')
current_dir_alt = os.listdir('')
print("Current directory contents:")
for item in current_dir:
print(item)
print("\nCurrent directory contents (alternative):")
for item in current_dir_alt:
print(item)
Both of these examples will list the contents of the current working directory.
Sorting the Results
By default, os.listdir()
returns the list of files and directories in an arbitrary order. If you need to sort the results, you can use the built-in sorted()
function:
import os
directory_path = '/home/user/documents'
file_list = sorted(os.listdir(directory_path))
for item in file_list:
print(item)
This will output the list of files and directories in alphabetical order.
Filtering the Results
In some cases, you may want to filter the results returned by os.listdir()
to only include certain types of files or directories. You can achieve this by using list comprehension or the filter()
function:
import os
directory_path = '/home/user/documents'
only_directories = [item for item in os.listdir(directory_path) if os.path.isdir(os.path.join(directory_path, item))]
only_files = list(filter(lambda x: os.path.isfile(os.path.join(directory_path, x)), os.listdir(directory_path)))
print("Directories:")
for item in only_directories:
print(item)
print("\nFiles:")
for item in only_files:
print(item)
This example will separate the contents of the /home/user/documents
directory into two lists: one containing only directories and the other containing only files.
By understanding the basic usage and features of os.listdir()
, you can now move on to more advanced file listing techniques, which we'll cover in the next section.