【问题标题】:python read all files in directory and subdirectoriespython读取目录和子目录中的所有文件
【发布时间】:2014-11-10 03:56:04
【问题描述】:

我正在尝试在 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 文件

-> 过滤字符串 "video" "player" 以找到视频应用程序

-> 过滤字符串“nodisplay=true”和“audio”以不显示音频播放器和无 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

但是递归文件有问题...

我该如何解决? 谢谢

【问题讨论】:

  • 请在您的问题中包含所需的行为。

标签: python file subdirectory


【解决方案1】:

看起来您的 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:

【讨论】:

  • 这行得通,谢谢。我知道我的代码很糟糕,但我不知道怎么问!再次感谢。
  • 谢谢。没问题:)
猜你喜欢
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 2013-12-02
  • 1970-01-01
  • 2012-11-14
相关资源
最近更新 更多