python實現在目錄中尋找指定檔案的方法

來源:互聯網
上載者:User
本文執行個體講述了python實現在目錄中尋找指定檔案的方法。分享給大家供大家參考。具體實現方法如下:

1. 模糊尋找

代碼如下:

import os
from glob import glob #用到了這個模組
def search_file(pattern, search_path=os.environ['PATH'], pathsep=os.pathsep):
for path in search_path.split(os.pathsep):
for match in glob(os.path.join(path, pattern)):
yield match
if __name__ == '__main__':
import sys
if len(sys.argv)<2 or sys.argv[1].startswith('-'):#sys.argv[0]是當前路徑,1開始是後面的參數
print 'Use: %s ' % sys.argv[0]
sys.exit(1)
if len(sys.argv)>2:
matchs = list(search_file(sys.argv[1],sys.argv[2]))
else:
matchs = list(search_file(sys.argv[1]))
print '%d match' % len(matchs)
for match in matchs:
print match


2. 指定的檔案名稱精確尋找

代碼如下:

import os,optparse
#1:精確尋找
def search_file(filename, search_path=os.environ['PATH'], pathsep=os.pathsep):#os.pathsep是分隔字元';'
for path in search_path.split(os.pathsep):
candidate = os.path.join(path, filename)#預選路徑
if os.path.isfile(candidate):
yield os.path.abspath(candidate) #用產生器可以方便控制返回的資料.可以使用.next()等方法只返回下一個子項
def parse_args():#協助提示
usage = u'''這是一個尋找檔案夾路徑中是否有檔案指定檔案的指令碼,
第一個參數是要找的檔案名稱,第二個是路徑'''
parser = optparse.OptionParser(usage)
help = u'要尋找的檔案名稱字'
parser.add_option('--filename', help=help)#type='int',
help = u'尋找的路徑多個路徑以;分隔'
parser.add_option('--path', help=help, default='e:')
options, args = parser.parse_args()
return options, args
if __name__ == '__main__':
options, args = parse_args()
find_file = list(search_file(args[0], args[1]))
if find_file:
for file in find_file:
print "Found File at %s" % file
else:
print "Not Found"



例子:在e:/py和e:/phpwww目錄下找以a到d開頭的.php的檔案
E:py>python_cook [a-d]*.php e:/py;e:/phpwww
2 match
e:/phpwwwcurl.php
e:/phpwwwduoxiancheng.php

希望本文所述對大家的Python程式設計有所協助。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.