python读取目录和子目录中的所有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25868109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python read all files in directory and subdirectories
提问by Guillaume
I'm trying to translate this bash line in python:
我正在尝试在 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
The result is to show all the videos apps installed in a Ubuntu system.
结果是显示安装在 Ubuntu 系统中的所有视频应用程序。
-> read all the .desktop files in /usr/share/applications/ directory
-> 读取 /usr/share/applications/ 目录中的所有 .desktop 文件
-> filter the strings "video" "player" to find the video applications
-> 过滤字符串“video”“player”以查找视频应用程序
-> filter the string "nodisplay=true" and "audio" to not show audio players and no-gui apps
-> 过滤字符串 "nodisplay=true" 和 "audio" 以不显示音频播放器和无 gui 应用程序
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
我该如何解决?谢谢
采纳答案by Mikko Ohtamaa
Looks like you are doing os.walk()loop incorrectly. There is no need for nested dir loop.
看起来你做os.walk()循环不正确。不需要嵌套的目录循环。
Please refer to Python manual for the correct example:
有关正确示例,请参阅 Python 手册:
https://docs.python.org/2/library/os.html?highlight=walk#os.walk
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:

