python自动查找电脑中的文件

如果你经常找不到文件,可以试试下面的代码:
代码的详细解释和说明

import os
import fnmatch
import easygui as g
searchPath = g.enterbox(msg='请输入文件查找目录',default='/Users/mac/Desktop')
fileName = g.enterbox(msg='请输入您要查找的文件名:',default='path.txt')

def searchFile(fileName,searchPath):
    file_list = []
    for path,dirnames,filenames in os.walk(searchPath):
        for filename in filenames:
            if fnmatch.fnmatch(fileName,filename):

                path1=os.path.join(path,filename)
                file_list.append(path1)
    if len(file_list) != 0:
        return file_list
    return -1 

answer = searchFile(fileName,searchPath)
if answer == -1:
    g.msgbox("查无此文件",'查找错误')
else:
    g.msgbox(answer,'返回路径')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容