首页主机资讯python cmd命令行怎样进行文件搜索

python cmd命令行怎样进行文件搜索

时间2025-09-28 23:10:04发布访客分类主机资讯浏览214
导读:在Python中,你可以使用os和fnmatch库来进行文件搜索 import os import fnmatch def search_files(pattern, path='.' : """ 在指定路径中搜索与给定模...

在Python中,你可以使用osfnmatch库来进行文件搜索

import os
import fnmatch

def search_files(pattern, path='.'):
    """
    在指定路径中搜索与给定模式匹配的文件。

    :param pattern: 要搜索的文件名模式,例如 "*.txt"
    :param path: 要搜索的路径,默认为当前目录
    :return: 匹配文件的列表
    """
    matched_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if fnmatch.fnmatch(file, pattern):
                matched_files.append(os.path.join(root, file))
    return matched_files

# 使用示例
pattern = "*.txt"  # 搜索所有txt文件
path = "/path/to/search"  # 要搜索的路径
matched_files = search_files(pattern, path)
print("匹配的文件:")
for file in matched_files:
    print(file)

pattern变量设置为你要搜索的文件名模式,将path变量设置为你要搜索的路径。这个函数会返回一个包含所有匹配文件的列表。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: python cmd命令行怎样进行文件搜索
本文地址: https://pptw.com/jishu/712035.html
python cmd命令行如何查看磁盘空间 python cmd命令行能进行网络请求吗

游客 回复需填写必要信息