繁体   English   中英

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

[英]python read all files in directory and subdirectories

我正在尝试在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”以不显示音频播放器和no-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

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

我该如何解决? 谢谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM