Python实现的本地文件搜索功能示例【测试可用】

作者:shw800 时间:2022-04-20 06:11:10 

本文实例讲述了Python实现的本地文件搜索功能。分享给大家供大家参考,具体如下:

偶尔需要搜索指定文件,不想每次都在windows下面去搜索,想用代码来实现搜索,而且能够收集搜索结果,于是有了下面的代码。


# -*- 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")

运行结果:

Python实现的本地文件搜索功能示例【测试可用】

更多Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

来源:https://blog.csdn.net/shw800/article/details/46443613

标签:Python,文件搜索
0
投稿

猜你喜欢

  • redis不能访问本机真实ip地址的解决方案

    2023-07-05 13:09:44
  • python 获取微信好友列表的方法(微信web)

    2022-02-20 10:05:21
  • Python中的flask框架详解

    2021-03-20 20:23:59
  • Python爬虫爬取商品失败处理方法

    2021-04-11 11:26:31
  • pandas 时间格式转换的实现

    2021-03-23 13:09:01
  • Python数据结构之二叉排序树的定义、查找、插入、构造、删除

    2022-03-03 08:19:51
  • jQuery打造动态下滑菜单

    2010-04-20 14:50:00
  • Javascript DOM 编程实例讲解--仿LightBox效果提示框

    2008-05-01 13:25:00
  • MySQL Server 5.0安装教程(图解)

    2010-10-14 14:26:00
  • python多项式拟合之np.polyfit 和 np.polyld详解

    2022-09-12 13:32:49
  • Python利用keras接口实现深度神经网络回归

    2021-02-07 12:01:41
  • SQL Server 2008 到底需要使用哪些端口?

    2012-11-30 20:29:41
  • Python安装spark的详细过程

    2021-05-17 09:59:05
  • Django博客系统注册之创建用户模块应用

    2021-08-06 15:15:20
  • 挑战! 纯Javascript 重现经典网游! <魔力宝贝>

    2008-10-04 10:37:00
  • Django利用AJAX技术实现博文实时搜索

    2023-01-02 01:57:50
  • 使用python 打开文件并做匹配处理的实例

    2022-01-15 16:27:30
  • python构造IP报文实例

    2023-07-10 20:40:51
  • 使用cookie和application实现在线人数统计

    2007-09-18 13:01:00
  • Python模块glob函数示例详解教程

    2023-10-27 15:49:36
  • asp之家 网络编程 m.aspxhome.com