使用python和通配符在目录中查找文件

时间:2018-07-22 07:44:27

标签: python python-2.7

如何使用python在目录中找到文件。我尝试使用glob,但无法获得一致的结果

我需要找到该文件,但是glob似乎没有将其拾取。 D:\ Temp \ projectartifacts \ drop \ projectartifacts \ vendor.c252f50265ea4005a6d8.js

glob.glob('D:\Temp\projectartifacts\drop\projectartifacts\vendor.*.js')

1 个答案:

答案 0 :(得分:3)

您可以使用python regex库在特定文件夹中找到所需的模式。 如果您具有文件夹路径,则只需对照此正则表达式检查所有文件名。

import os
import re

# Create the list of all your folder content with os.listdir()
folder_content = os.listdir(folder_path)

# Create a regex from the pattern
# with the regex, you want to find 'vendor.' --> 'vendor\.' (. needs to be escaped)
# then any alphanumeric characters --> '.*' (. is regex wildcard and .* means match 0 or more times any characters)
# then you want to match .js at the end --> '\.js'

regex_pattern = 'vendor\..*\.js'
regex = re.compile(regex_pattern)

# Search in folder content
res = ''
for path in folder_content:
    if regex.search(path):
        res = path
        break

print(res)