Skip to main content
 首页 » 编程设计

python之在文件夹中搜索包含子字符串的文件,python

2025年05月04日48xxx_UU

假设路径是 "c:\users\test",文件夹 "test"包含很多文件。我想在测试文件夹中搜索一个文件,文件名在 python 脚本中包含一个单词“postfix”。有人可以帮我吗?

请您参考如下方法:

glob module内置到 python 正是为此而制作的。

import glob 
path_to_folder = "/path/to/my/directory/" 
matching_files = glob.glob(path_to_folder+"*postfix*") 
for matching_file in matching_files: 
    print(matching_file) 

应该打印出所有包含“postfix”的文件,* 是匹配任何内容的通配符。因此,此模式将匹配 test_postfix.csv 以及 mypostfix.txt