您的位置:首页 > 理论基础

python学习——查找计算机中文件位置

2014-08-29 17:08 375 查看
有时想查找某个文件时,却忘记了文件在计算机中存放的位置,这是一个经常遇到的问题。

当然如果你使用windows 7的话,可以直接用右上角的搜索框来搜索。

最近在学习python,正好拿这个来练练手,写一个查找文件的脚本。

主要思路是遍历目录下所有的文件和子目录,与要查找的文件对比,如果匹配就放入查找结果。

import os,sys,pprint,time
def find(pattern,directory):
found =[]                            #Store the result
pattern = pattern.lower()            #Normalize to lowercase
#print(file_find)
for (thisdir,subsHere,filesHere) in os.walk(directory):
for file in filesHere + subsHere:#Search all the files and subdirect
if pattern in file.lower():
found.append(os.path.join(thisdir,file))
return found

if __name__=='__main__':
directory = input('Enter directory:\n')
pattern = input('Enter filename you search:\n')
t1 = time.clock()                     #Calculate the running time
found = find(pattern,directory)
t2 = time.clock()
print(t2-t1)
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的具体位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: