歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python:在指定目錄下查找滿足條件的文件

Python:在指定目錄下查找滿足條件的文件

日期:2017/3/1 9:26:36   编辑:Linux編程

1. Python在指定目錄及其子目錄中查找文件名含有關鍵字的文件

源碼

#search.py
import os
import sys

def search(path, word):
for filename in os.listdir(path):
fp = os.path.join(path, filename)
if os.path.isfile(fp) and word in filename:
print fp
elif os.path.isdir(fp):
search(fp, word)

search(sys.argv[1], sys.argv[2])

使用

python search.py directory_path keyword

2. 在制定目錄及其子目錄中查找文件內容含有關鍵字的文件

源碼

#search.py
import os
import sys

def search(path, word):
for filename in os.listdir(path):
fp = os.path.join(path, filename)
if os.path.isfile(fp):
with open(fp) as f:
for line in f:
if word in line:
print fp
break
elif os.path.isdir(fp):
search(fp, word)

search(sys.argv[1], sys.argv[2])

使用

python search.py directory_path keyword

Python2.7.7源碼分析 http://www.linuxidc.com/Linux/2015-08/121168.htm

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved