python读取目录和子目录中的所有文件

时间:2014-09-16 11:54:55

标签: python file subdirectory

我试图在python中翻译这个bash行:

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

结果是显示Ubuntu系统中安装的所有视频应用。

- >读取/ usr / share / applications /目录中的所有.desktop文件

- >过滤字符串"视频" "播放"找到视频应用程序

- >过滤字符串" nodisplay = true"和"音频"不显示音频播放器和无gui应用程序

我想要的结果是(例如):

kmplayer
smplayer
vlc
xbmc

所以,我尝试过这段代码:

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

但我对递归文件有问题......

我该如何解决? 感谢

1 个答案:

答案 0 :(得分:17)

看起来你正在os.walk()循环错误。不需要嵌套的dir循环。

请参阅Python手册以获取正确的示例:

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: