前言
初学Python,总想搞点事情提高自己的学习兴趣,当然有些部分也是借鉴了前辈们的经验——使用walk()函数遍历目录和文件感觉方便的多
利用OS模块实现文件查找
编写环境:pycharm、Python3.5
1. 导入程序需要的模块
import os # 引入操作系统模块
import time
import easygui as eg # 引入图形用户界面
import sys
import string
2.获取当前计算机磁盘目录
def get_disk():
disk_list = []
for disk in string.ascii_uppercase:
disk = disk + ':\\'
if os.path.exists(disk):
disk_list.append(disk)
return disk_list
3.定义存储搜索结果的全局列表对象
all_search_file = []
4.搜索部分功能实现
如果要加上 '$' not in AllFile
这段代码,需要将AllFile = os.path.join(root, file)
前置
# 搜索包含关键字的目录
def searchDirs(root, name, dirs):
for _dir in dirs:
if -1 != _dir.find(name) and _dir[0] != '$':
AllDir = os.path.join(root, _dir)
all_search_file.append(AllDir)
# 搜索包含关键字的文件
def searchFiles(root, name, files):
for file in files:
if name in file: # '$' not in AllFile 去除隐藏文件
AllFile = os.path.join(root, file)
all_search_file.append(AllFile)
def search(name):
curdisks = get_disk()
try:
for disk in curdisks:
for root, dirs, files in os.walk(disk, True):
searchDirs(root, name, dirs)
searchFiles(root, name, files)
except:
sys.exit(0)
5.程序界面显示部分
def main():
input_name = eg.enterbox(msg='请输入您要查找的文件名:')
if input_name == '' or input_name == ' ':
main()
else:
start_time = time.time()
search(input_name)
end_time = time.time()
timeout = end_time - start_time
while all_search_file:
choice = eg.choicebox("本次搜索大约用了 %.2f 秒,结果如下:" % timeout,
"与 【%s】 相关文件" % input_name, choices=all_search_file)
if choice and choice != 'Add more choices':
os.startfile(r'' + choice) # 打开文件或所在位置
else:
break
else:
eg.msgbox("查无此文件", '查找错误')
main()
6.运行结果
你也可以访问以下链接获取打包好的程序文件:
链接:https://pan.baidu.com/s/18GRb704R8efy-vStezcrsA
提取码:zgio
结语
功能上实现了,不过性能的优化上可能还有改进的地方。。。