Python實現(xiàn)的本地文件搜索功能示例【測試可用】
本文實例講述了Python實現(xiàn)的本地文件搜索功能。分享給大家供大家參考,具體如下:
偶爾需要搜索指定文件,不想每次都在windows下面去搜索,想用代碼來實現(xiàn)搜索,而且能夠收集搜索結(jié)果,于是有了下面的代碼。
# -*- coding:utf-8 -*- #! python2 import os def search_file(fileNmae, path): '''search a file in target directory :param fileNmae: file to be searched :param path: search scope :return:file list ''' flag = False count = 0 result_list = [] if os.path.exists(path): for root, dirs, files in os.walk(path): for fn in files: Name = fn.decode('gbk') cu_path = root.encode('gbk')+"\\"+Name if Name.lower().find(fileNmae.lower()) != -1 and os.path.isfile(cu_path): print ":::Find it,file no", count+1, ":", cu_path flag = True count += 1 result_list.append(cu_path) if flag is False: print ":::Not found the file:", fileNmae, "in path:", path else: print "======== Get[", count, "]files ========" return result_list else: print "!!-----path not existed:", path #測試: search_file("4.jpg", "C:\\img")
運行結(jié)果:
更多Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關(guān)文章
Python計算圖片數(shù)據(jù)集的均值方差示例詳解
這篇文章主要為大家介紹了Python計算圖片數(shù)據(jù)集的均值方差,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05Pandas中Concat與Append的實現(xiàn)與區(qū)別小結(jié)
本文主要介紹了Pandas中Concat與Append的實現(xiàn)與區(qū)別小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11anaconda中Conda創(chuàng)建虛擬環(huán)境的實現(xiàn)步驟
在Anaconda中,可以使用conda命令來創(chuàng)建和管理虛擬環(huán)境,本文主要介紹了anaconda中Conda創(chuàng)建虛擬環(huán)境的實現(xiàn)步驟,具有一定的參考價值,感興趣的可以了解一下2023-12-12關(guān)于tensorflow softmax函數(shù)用法解析
這篇文章主要介紹了關(guān)于tensorflow softmax函數(shù)用法解析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python3 實現(xiàn)減少可調(diào)用對象的參數(shù)個數(shù)
今天小編就為大家分享一篇Python3 實現(xiàn)減少可調(diào)用對象的參數(shù)個數(shù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12