python學習——查找計算機中文件位置


有時想查找某個文件時,卻忘記了文件在計算機中存放的位置,這是一個經常遇到的問題。

當然如果你使用windows 7的話,可以直接用右上角的搜索框來搜索。

最近在學習python,正好拿這個來練練手,寫一個查找文件的腳本。

主要思路是遍歷目錄下所有的文件和子目錄,與要查找的文件對比,如果匹配就放入查找結果。

 1 import os,sys,pprint,time
 2 def find(pattern,directory):
 3     found =[]                            #Store the result
 4     pattern = pattern.lower()            #Normalize to lowercase
 5     #print(file_find)
 6     for (thisdir,subsHere,filesHere) in os.walk(directory):
 7         for file in filesHere + subsHere:#Search all the files and subdirect
 8             if pattern in file.lower():
 9                 found.append(os.path.join(thisdir,file))
10     return found
11 
12 if __name__=='__main__':
13     directory = input('Enter directory:\n')
14     pattern = input('Enter filename you search:\n')
15     t1 = time.clock()                     #Calculate the running time
16     found = find(pattern,directory)
17     t2 = time.clock()
18     print(t2-t1)
19     pprint.pprint(found[:])               #Print the result

 下面是在我自己的電腦上運行的例子

首先在E盤下建一個abc.txt,我們將它放在E:\video\六人行\[Friends.S01]\abc.txt

假設現在我們忘記了abc.txt具體在哪個目錄下,只知道在E盤下。

我們用上面的腳本來查找,下面是運行的結果

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Enter directory:
E:\
Enter filename you search:
abc.txt
1.428899593268289
['E:\\video\\六人行\\[Friends.S01]\\abc.txt']
>>> 

可以看到用時1.4s查到了abc.txt的具體位置。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM