【问题标题】:Using Python to search specific file names in (sub)folders使用 Python 在(子)文件夹中搜索特定文件名
【发布时间】:2020-02-08 16:15:48
【问题描述】:

我正在尝试使用 GUI 进行文件搜索、基于 Python 的程序。 它将用于搜索指定的目录和子目录。对于必须在输入框中插入文件名的文件。 虽然我对 python 编程还很陌生,但我在网上搜索并获得了一些关于 os 模块的信息。

然后我继续尝试使用os.walk 编写一个简单的代码,并且不使用 GUI 程序:

import os
for root, dirs, files in os.walk( 'Path\to\files'):
    for file in files:
       if file.endswith('.doc'):
        print(os.path.join(root, file))

这很好用,但是...file.endswith() 只查看文件名的最后一部分。 问题是文件路径中有超过 1000 个带有 .doc 的文件。我希望代码能够搜索文件名部分,例如文件名“Hilka_Vernier_Caliper.xml”中的“Caliper”。文档”。

于是我继续搜索file.endswith()以外的其他方法,发现了一些关于file.index()的信息。所以我把代码改成:

import os
    for root, dirs, files in os.walk( 'Path\to\files'):
        for file in files:
           if file.index('Caliper'):
            print(os.path.join(root, file))

但这并没有按计划进行...... 这里有人有想法吗,我怎么能做到这一点?

【问题讨论】:

    标签: python-3.x windows search directory


    【解决方案1】:

    您可以使用pathlib 代替旧的oshttps://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob

    顺便说一句,如果找不到名称,file.index 会引发异常,因此您需要一个 try/except 子句。

    另一种方法是使用if "Caliper" in str(file):

    【讨论】:

    • 感谢您的评论 vpoulailleau,我将深入研究 pathlib :-)
    猜你喜欢
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多