Python reads all files in a directory and subdirectories

I am trying to translate this bash line into python:

find /usr/share/applications/ -name "*.desktop" -exec grep -il "player" {} \; | sort | while IFS=$'\n' read APPLI ; do grep -ilqw "video" "$APPLI" && echo "$APPLI" ; done | while IFS=$'\n' read APPLI ; do grep -iql "nodisplay=true" "$APPLI" || echo "$(basename "${APPLI%.*}")" ; done


As a result, you will see all video applications installed on the Ubuntu system.

-> read all .desktop files in / usr / share / applications / directory

-> filter strings "video" "player" to find video attachments

-> filter the string "nodisplay = true" and "audio" to not show audio players and applications without gui

The result I would like to have (for example):



So I tried this code:

import os
import fnmatch

apps = []
for root, dirnames, filenames in os.walk('/usr/share/applications/'):
   for dirname in dirnames:
     for filename in filenames:
        with open('/usr/share/applications/' + dirname + "/" + filename, "r") as auto:
            a =
            if "Player" in a or "Video" in a or "video" in a or "player" in a:
              if "NoDisplay=true" not in a or "audio" not in a:
                  print "OK: ", filename
                  filename = filename.replace(".desktop", "")

print apps


But I have a problem with recursive files ...

How can I fix this? Thanks to


source to share

1 answer

It looks like you are looping wrong os.walk()

. There is no need for a nested loop.

For a correct example, refer to the Python manual:

for root, dirs, files in os.walk('python/Lib/email'):
     for file in files:
        with open(os.path.join(root, file), "r") as auto:




All Articles