Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

python read all files in directory and subdirectories

I'm trying to translate this bash line in python:

find /usr/share/applications/ -name "*.desktop" -exec grep -il "player" {} ; | sort | while IFS=$'
' read APPLI ; do grep -ilqw "video" "$APPLI" && echo "$APPLI" ; done | while IFS=$'
' 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...