-2

How do I find a file in directory using python. I tried using glob but not able to get consistant results

I need to find this file but glob does not seem to pick it up. D:\Temp\projectartifacts\drop\projectartifacts\vendor.c252f50265ea4005a6d8.js

glob.glob('D:\Temp\projectartifacts\drop\projectartifacts\vendor.*.js')
kumar
  • 8,207
  • 20
  • 85
  • 176
  • 2
    what results are you expecting and what are you getting? – aydow Jul 22 '18 at 07:47
  • Possible duplicate of [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – agtoever Jul 22 '18 at 08:11
  • Please tell us more details – Stephen Fong Jul 22 '18 at 08:39
  • Possible duplicate of [get file path using backslash (\‌) in windows in python](https://stackoverflow.com/questions/17756485/get-file-path-using-backslash-in-windows-in-python) – SiHa Jul 22 '18 at 09:52

1 Answers1

3

You can use the python regex library to find the desired pattern in a specific folder. If you have the folder path, you just have to check all files names against this 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)