美文网首页
Python—多线程文件名称查找

Python—多线程文件名称查找

作者: Ackerzy | 来源:发表于2018-07-24 00:03 被阅读31次

该脚本的功能为:
对某一文件夹启动任意个线程查找文件包含XXX字符的文件名,并显示该文件所在的路径

# Python 3.6.1
import os
import time
from queue import Queue
from threading import Thread

queue = Queue()

# 搜索一个路径下的所有文件名
def mylistdir(path):
    files = os.listdir(path)
    for file in files:
        pfile = path + "/" + file
        if os.path.isdir(pfile):
            mylistdir(pfile)
        if os.path.isfile(pfile):
            s.append(pfile)
    return s

# 线程搜索
class SearchThread(Thread):
    def __init__(self, queue):
        Thread.__init__(self)
        self.queue = queue
    def run(self):
        global key
        while True:
            files = self.queue.get()
            if key in files:
                file_result.append(files)
            self.queue.task_done()

# 一些配置信息
s = []
file_result = []
path = input('请输入目录(示例:C:/Users/Amber/Desktop/Python):')
key = input('请输入关键字:')
threads = int(input('请输入线程数:'))
start = time.time()
mylistdir(path)

# 生成10个线程
for i in range(threads):
    t = SearchThread(queue)
    t.start()

# 向队列中填充数据
for file in s:
    queue.put(file)

queue.join()

# 将结果写入文件
with open('C:/Users/Amber/Desktop/test.txt', 'w', encoding='utf-8') as f:
    for i in file_result:
        f.write(i)
        f.write('\n')
print("花费时间: %s" % (time.time() - start))

运行结果:

1.PNG 2.PNG

还没有进一步优化,欢迎大家留言评论,帮助小白改进脚本(✪ω✪)。

相关文章

  • Python—多线程文件名称查找

    该脚本的功能为:对某一文件夹启动任意个线程查找文件包含XXX字符的文件名,并显示该文件所在的路径 运行结果: 还没...

  • find命令

    查找文件 find [路径] [参数] [条件] -name 按文件名称查找 find /etc/ -name ...

  • python多线程与多进程

    Python是运行在解释器中的语言,查找资料知道,python中有一个全局锁(GIL),在使用多线程(Thread...

  • 简单的linux文件查找命令

    1、查找文件 2、查找文件夹(目录) 3、查找内容 4、只显示文件名称

  • Find 命令 搜索文件/文件夹 Linux/Mac

    Find 命令 根据文件名称模糊查询 查找属主文件 根据文件类型查找 根据文件大小查找 根据时间查找文件 根据权限...

  • python3 批量替换文件名称

    python3 批量替换文件名称

  • 【linux】文件查找

    一.find 通过文件名称查找 通过文件名模糊匹配 指定查找范围 通过用户名称查找 指定文件大小 二.locate...

  • python flask接收前端post请求

    html部分,保存文件名称为index.html python部分,保存文件名称为request.py 第一步: ...

  • pip

    Python2 的路径查找命令:witch python Python3 的路径查找命令:which python...

  • GIL

    谈谈python的GIL、多线程、多进程 最近在看 Python 的多线程,经常我们会听到老手说:“python下...

网友评论

      本文标题:Python—多线程文件名称查找

      本文链接:https://www.haomeiwen.com/subject/yovsmftx.html