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的具体位置。