Python os.listdir() Method Example
The listdir() and system() functions belong to the OS module. The OS module in Python involves methods that are used to interact with your operating system, performing actions like:
- Creating a new folder or directory.
- Renaming an existing folder.
- Deleting a directory.
- Displaying the path to your current working directory.
How to Import the OS Module
To use the os module in your script, you need to “import” it. Importing a module means gaining access to all the functions and variables that are stored within the module.
import os
This will give you access to all the functions defined in the os module. Let’s talk about os.listdir() method.
Python os.listdir()
Python os.listdir() is an inbuilt method that returns a list containing the names of the entries in the directory given by path. The returned list is in arbitrary order, and it does not constitute the special entries ‘.’ and ‘..’ even if they are present in the directory.
Syntax
os.listdir(path)
Parameters
The listdir() function takes a path as a parameter, which is a directory, which needs to be explored.
Return Value
The listdir() method returns a list containing the names of the entries in the directory given by path.
Example
import os # Open a file path = "/Users/krunal/Desktop/code/pyt/database" dirs = os.listdir(path) # This would print all the files and directories for file in dirs: print(file)
Output
shows.csv Netflix.csv marketing.csv new_file.json data.json Netflix shows.db app.py .vscode purchase.csv final.zip sales.csv
And we get all the files in our current project directory.
Passing no path parameter
If we don’t specify any folder, then the list of files and directories in the current working directory will be returned.
import os # Open a file dirs = os.listdir() # This would print all the files and directories for file in dirs: print(file)
Output
shows.csv Netflix.csv marketing.csv new_file.json data.json Netflix shows.db app.py .vscode purchase.csv final.zip sales.csv
Python OS.listdir() and endswith( )
We can use the combination of listdir() and endswith() function to search for a specific file and print its content or do whatever you want.
Let’s find the json files in our folder and print their names.
See the following code.
import os items = os.listdir(".") data = [] for names in items: if names.endswith(".json"): data.append(names) print(data)
Output
['new_file.json', 'data.json']
And we got two json files because my current directory has two json files.
That is it for the Python os.listdir() method.