Hello coders!! This article will be learning about the os.listdir function in Python. The os module allows us to use the functionality dependent on the operating system in a portable manner. listdir() is a method available in the os module. It returns a list containing the contents of the directory given by path. Let us learn about this topic in detail.
What is the os.listdir() method in Python?
It is a method available in the os module of Python. This method is used to retrieve the list of files and directories present in the specified directory. In case the directory is not specified, the contents of the present working directory are returned.
- SYNATX: os.listdir(path)
- PARAMETERS: It is optional. It contains the path of the directory.
- RETURN VALUE: a list containing the entries’ names in the directory given by path.
Let us see some illustrated examples to use listdir() using Python.
Example 1: To get the files and directories in root directory using listdir():
import os path = "/" dirct = os.listdir(path) print("Files and directories:") print(dirct)
Output & Explanation:
OutputIn this example, we selected the root directory as our desired path. We then used the listdir() method to get the list of directories and files present inside the root directory.
Example 2: To get the files and directories in present working directory:
import os path = os.getcwd() dirct = os.listdir(path) print("Path:") print(path) print() print("Files and directories:") print(dirct)
Output & Explanation:
OutputWe first used the getcwd() method to get the path of the current working directory. We then passed this path as a parameter to the method to retrieve the contents of the current working directory.
Example 3: Not using the path parameter in listdir() In Python:
import os dirct = os.listdir() print("Files and directories:") print(dirct)
Output & Explanation:
OutputIn this particular example, we did not pass the path parameter of the function. As a result, the function automatically took the path of the current working directory, thus returning the contents of the same.
Example 4: loop listdir in try-except using Python:
def loop(): try: for txt in os.listdir(path): if txt.endswith(txt_extension): print(path + txt) except KeyboardInterrupt: exit()
In this code, we have iterated through the directory’s contents to look for the files having ‘txt_extension’ inside the try-except block. If the file having the specified extension is received, its name and path are printed. We have used the inbuilt KeyboardInterrupt exception. This exception is raised when the user clicks an interrupt key like ctrl+c.
Example 5: Python listdir sort by date:
import glob import os file = glob.glob("*.ipynb") file.sort(key=os.path.getmtime) print("\n".join(files))
Output & Explanation:
We have used the glob module, which is used to find all the pathnames matching a specified pattern. We then used the sort() method to sort the files with the extension ‘ipynb’ according to time. By default, the result is sorted by name.
Example 6: Python listdir sort by name:
import os dirct = os.listdir() print("Files and directories:") print(dirct.sort())
Output & Explanation:
Here, we have used the sort() method to sort the contents of the directory as per the name. Anyway, by default, the output of os.listdir() will be sorted as per the name only.
Example 7: Python listdir absolute path:
import os absp = os.path.abspath(os.getcwd()) print("Full path: " + absp) print("Directory Path: " + os.path.dirname(absp))
Output & Explanation:
Here, we have used the abspath() method to get the absolute path of the current directory. We then used the dirname() method to get the given absolute path’s directory path.
Example 8: Python listdir with specific extension:
import glob import os file = glob.glob("*.ipynb") file.sort(key=os.path.getmtime) print("\n".join(files))
Output & Explanation:
As we can see, here we have extracted only the files having the extension ‘ipynb’ using the glob module.
Conclusion | Python os.listdir():
With this, we come to an end to this article. I hope it was easy to understand the concept of listdir() in python and the various ways in which it can be used to extract the contents at a given path.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Happy Pythoning!
The post 8 Examples to Implement os.listdir() in Python appeared first on Python Pool.
from Planet Python
via read more
No comments:
Post a Comment