[英]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.