DEV Community

petercour
petercour

Posted on

Listing files, dirs and subdirs with Python

If you know Python programming, there's a lot of things you can do. You can use the os module to list all files in the directory (including subdirectories).

If you use Linux or Mac, you can even list every file on your computer (search from /). Or you could browse from your home directory.

If you want all files from the current directory and subdirs, use '.'.

#!/usr/bin/python3
import os
path = '.'
for dirpath, dirname, filenames in os.walk(path):
    for filename in filenames:
        print(os.path.join(dirpath,filename))
Enter fullscreen mode Exit fullscreen mode

This lists all files in the directory, including all hidden files.
For readability you can change it to:

#!/usr/bin/python3
...
    file_and_path = os.path.join(dirpath,filename)
    print(file_and_path)
Enter fullscreen mode Exit fullscreen mode

File interaction

You can show only specific files and interact with them. For instance, you can show every image on your computer

#!/usr/bin/python3
import os
import cv2
import time

path = '/home/linux/Desktop'
for dirpath, dirname, filenames in os.walk(path):
    for filename in filenames:
        file_and_path = os.path.join(dirpath,filename)
        if ".jpg" in file_and_path or ".jpeg" in file_and_path:
            print(file_and_path)

            try:
                # show image
                image = cv2.imread(file_and_path)
                cv2.imshow(file_and_path, image)
                cv2.waitKey(2000)
                cv2.destroyAllWindows()
                #time.sleep(1)
            except:
                print('Error loading image ' + file_and_path)
Enter fullscreen mode Exit fullscreen mode

Related links:

Top comments (0)