Python实现文件查询关键字功能的示例详解

 更新时间:2026年02月12日 09:52:17   作者:豆本-豆豆奶  
这篇文章主要为大家详细介绍了Python实现文件查询关键字功能,文中的示例详解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下

咱们可以想象一个这样的场景,你这边有大量的文件,现在我需要查找一个 序列号:xxxxxx,我想知道这个 序列号:xxxxxx 在哪个文件中。

在没有使用代码脚本的情况下,你可能需要一个文件一个文件打开,然后按 CTRL+F 来进行搜索查询。

那既然我们会使用 python,何不自己写一个呢?本文将实现这样一个工具,且源码全在文章中,只需要复制粘贴即可使用。

思路

主要思路就是通过打开文件夹,获取文件,一个个遍历查找关键字,流程图如下:

流程图

怎么样,思路非常简单,所以其实实现也不难。

本文将支持少部分文件类型,更多类型需要读者自己实现:

  • txt
  • docx
  • csv
  • xlsx
  • pptx

读取txt

安装库

pip install chardet

代码

import chardet


def detect_encoding(file_path):
    raw_data = None
    with open(file_path, 'rb') as f:
        for line in f:
            raw_data = line
            break

        if raw_data is None:
            raw_data = f.read()
    result = chardet.detect(raw_data)
    return result['encoding']


def read_txt(file_path, keywords=''):
    is_in = False
    encoding = detect_encoding(file_path)
    with open(file_path, 'r', encoding=encoding) as f:
        for line in f:
            if line.find(keywords) != -1:
                is_in = True
                break

    return is_in

我们使用了 chardet 库来判断 txt 的编码,以应对不同编码的读取方式。

读取docx

安装库

pip install python-docx

代码

from docx import Document


def read_docx(file_path, keywords=''):
    doc = Document(file_path)
    is_in = False

    for para in doc.paragraphs:
        if para.text.find(keywords) != -1:
            is_in = True
            break

    return is_in

读取csv

代码

import csv


def read_csv(file_path, keywords=''):
    is_in = False

    encoding = detect_encoding(file_path)
    with open(file_path, mode='r', encoding=encoding) as f:
        reader = csv.reader(f)

        for row in reader:
            row_text = ''.join([str(v) for v in row])
            if row_text.find(keywords) != -1:
                is_in = True
                break

    return is_in

读取xlsx

安装库

pip install openpyxl

代码

from openpyxl import load_workbook


def read_xlsx(file_path, keywords=''):
    wb = load_workbook(file_path)
    sheet_names = wb.sheetnames

    is_in = False
    for sheet_name in sheet_names:
        sheet = wb[sheet_name]
        for row in sheet.iter_rows(values_only=True):
            row_text = ''.join([str(v) for v in row])
            if row_text.find(keywords) != -1:
                is_in = True
                break

    wb.close()

    return is_in

读取pptx

安装库

pip install python-pptx 

代码

from pptx import Presentation


def read_ppt(ppt_file, keywords=''):
    prs = Presentation(ppt_file)
    is_in = False
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_text_frame:
                text_frame = shape.text_frame
                for paragraph in text_frame.paragraphs:
                    for run in paragraph.runs:
                        if run.text.find(keywords) != -1:
                            is_in = True
                            break

    return is_in

文件夹递归

为了防止文件夹嵌套导致的问题,我们还有一个文件夹递归的操作。

代码

from pathlib import Path


def list_files_recursive(directory):
    file_paths = []

    for path in Path(directory).rglob('*'):
        if path.is_file():
            file_paths.append(str(path))

    return file_paths

完整代码

# -*- coding: utf-8 -*-
from pptx import Presentation
import chardet
from docx import Document
import csv
from openpyxl import load_workbook
from pathlib import Path


def detect_encoding(file_path):
    raw_data = None
    with open(file_path, 'rb') as f:
        for line in f:
            raw_data = line
            break

        if raw_data is None:
            raw_data = f.read()
    result = chardet.detect(raw_data)
    return result['encoding']


def read_txt(file_path, keywords=''):
    is_in = False
    encoding = detect_encoding(file_path)
    with open(file_path, 'r', encoding=encoding) as f:
        for line in f:
            if line.find(keywords) != -1:
                is_in = True
                break

    return is_in


def read_docx(file_path, keywords=''):
    doc = Document(file_path)
    is_in = False

    for para in doc.paragraphs:
        if para.text.find(keywords) != -1:
            is_in = True
            break

    return is_in


def read_csv(file_path, keywords=''):
    is_in = False

    encoding = detect_encoding(file_path)
    with open(file_path, mode='r', encoding=encoding) as f:
        reader = csv.reader(f)

        for row in reader:
            row_text = ''.join([str(v) for v in row])
            if row_text.find(keywords) != -1:
                is_in = True
                break

    return is_in


def read_xlsx(file_path, keywords=''):
    wb = load_workbook(file_path)
    sheet_names = wb.sheetnames

    is_in = False
    for sheet_name in sheet_names:
        sheet = wb[sheet_name]
        for row in sheet.iter_rows(values_only=True):
            row_text = ''.join([str(v) for v in row])
            if row_text.find(keywords) != -1:
                is_in = True
                break

    wb.close()

    return is_in


def read_ppt(ppt_file, keywords=''):
    prs = Presentation(ppt_file)
    is_in = False
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_text_frame:
                text_frame = shape.text_frame
                for paragraph in text_frame.paragraphs:
                    for run in paragraph.runs:
                        if run.text.find(keywords) != -1:
                            is_in = True
                            break

    return is_in


def list_files_recursive(directory):
    file_paths = []

    for path in Path(directory).rglob('*'):
        if path.is_file():
            file_paths.append(str(path))

    return file_paths


if __name__ == '__main__':
    keywords = '测试关键字'
    file_paths = list_files_recursive(r'测试文件夹')
    for file_path in file_paths:
        if file_path.endswith('.txt'):
            is_in = read_txt(file_path, keywords)
        elif file_path.endswith('.docx'):
            is_in = read_docx(file_path, keywords)
        elif file_path.endswith('.csv'):
            is_in = read_csv(file_path, keywords)
        elif file_path.endswith('.xlsx'):
            is_in = read_xlsx(file_path, keywords)
        elif file_path.endswith('.pptx'):
            is_in = read_ppt(file_path, keywords)

        if is_in:
            print(file_path)

结尾

现在你可以十分方便地使用代码查找出各种文件中是否存在关键字了

以上就是Python实现文件查询关键字功能的示例详解的详细内容,更多关于Python查询文件关键字的资料请关注脚本之家其它相关文章!

相关文章

  • 解决json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误

    解决json.decoder.JSONDecodeError: Expecting value:&n

    这篇文章主要介绍了解决json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • win10环境下配置vscode python开发环境的教程详解

    win10环境下配置vscode python开发环境的教程详解

    这篇文章主要介绍了win10环境下配置python开发环境(vscode)的教程,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-10-10
  • python调用sikulixide库实现自动化脚本方法实例

    python调用sikulixide库实现自动化脚本方法实例

    SikuliX IDE是一个基于图像识别的自动化测试工具,主要用于UI测试,它本身并不直接支持文本文件读取操作,因为它主要用于处理屏幕上的图片和截图,这篇文章主要介绍了python调用sikulixide库实现自动化脚本的相关资料,需要的朋友可以参考下
    2025-11-11
  • 查看django执行的sql语句及消耗时间的两种方法

    查看django执行的sql语句及消耗时间的两种方法

    今天小编就为大家分享一篇查看django执行的sql语句及消耗时间的两种方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • 解决numpy和torch数据类型转化的问题

    解决numpy和torch数据类型转化的问题

    这篇文章主要介绍了解决numpy和torch数据类型转化的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • Python3基础之基本数据类型概述

    Python3基础之基本数据类型概述

    这篇文章主要介绍了Python3的基本数据类型,需要的朋友可以参考下
    2014-08-08
  • 如何通过Django使用本地css/js文件

    如何通过Django使用本地css/js文件

    这篇文章主要介绍了如何通过Django使用本地css/js文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • Python命令行中引导用户指定选择文档示例

    Python命令行中引导用户指定选择文档示例

    这篇文章主要为大家介绍了Python命令行中引导用户指定选择文档示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • Python求两点之间的直线距离(2种实现方法)

    Python求两点之间的直线距离(2种实现方法)

    今天小编就为大家分享一篇Python求两点之间的直线距离(2种实现方法),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • Python如何使用opencv进行手势识别详解

    Python如何使用opencv进行手势识别详解

    目前,人们正需要研发以人为中心进行计算机交互控制,所以下面这篇文章主要给大家介绍了关于Python如何使用opencv进行手势识别的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-01-01

最新评论