python read all files in directory and subdirectories

Guillaume picture Guillaume · Sep 16, 2014 · Viewed 28.4k times · Source

I'm trying to translate this bash line in 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

The result is to show all the videos apps installed in a Ubuntu system.

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

-> filter the strings "video" "player" to find the video applications

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

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

kmplayer
smplayer
vlc
xbmc

So, I've 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 = auto.read(50000)
            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", "")
                  apps.append(filename)

print apps

But I've a problem with the recursive files...

How can I fix it? Thanks

Answer

Mikko Ohtamaa picture Mikko Ohtamaa · Sep 16, 2014

Looks like you are doing os.walk() loop incorrectly. There is no need for nested dir loop.

Please refer to Python manual for the correct example:

https://docs.python.org/2/library/os.html?highlight=walk#os.walk

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