Os.listdir Python Code Example

Last Updated On Saturday 4th Dec 2021
  • Use os.listdir() function to get a list of all files and sub-directories in the current working directory.
  • Strings startswith() and endswith() methods for filtering the contents of a directory is also useful

Here’s the simple example

	import os

for filename in os.listdir(yourPath):
    if filename.endswith(".jpg") or filename.endswith(".png") or finlename.endswith("svg"):
        # ..Do Something with fileName
    else:
        continue