DEV Community

petercour
petercour

Posted on

3

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:

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay