python读取目录和子目录中的所有文件 [英] python read all files in directory and subdirectories
问题描述
我正在尝试在python中翻译此bash行:
I'm trying to translate this bash line in python:
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系统中安装的所有视频应用.
The result is to show all the videos apps installed in a Ubuntu system.
->读取/usr/share/applications/目录中的所有.desktop文件
-> read all the .desktop files in /usr/share/applications/ directory
->过滤字符串"video""player"以找到视频应用程序
-> filter the strings "video" "player" to find the video applications
->过滤字符串"nodisplay = true"和"audio"以不显示音频播放器和no-gui应用
-> 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...
我该如何解决? 谢谢
推荐答案
好像您在错误地执行os.walk()
循环.不需要嵌套的dir循环.
Looks like you are doing os.walk()
loop incorrectly. There is no need for nested dir loop.
有关正确的示例,请参阅Python手册:
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:
这篇关于python读取目录和子目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!