'Opening file from path without knowing full file name (python)

I am trying to open a file using the full path, but I don't know the complete name of the file, just a unique string within it.

i = identifier
doc = open(r'C:\my\path\*{0}*.txt'.format(i), 'r')

Now obviously this doesn't work because I'm trying to use the wildcard along with the raw string. I have had a lot of trouble in the past trying to use file paths without preceding them with 'r', so I'm not sure of the best way to handle the incomplete file name. Should I just forget raw string notation and use '\\\\' for the file path?



Solution 1:[1]

From the question comments:

import glob
import os

i = "identifier"
basePath = r"C:\my\path"

filePaths = glob.glob(os.path.join(basePath,'*{0}*.txt'.format(i)))

# Just open first ocurrence, if any
if filePaths:
    print "Found: ", filePaths[0]
    doc = open(filePaths[0], 'r')

Solution 2:[2]

import os 
    
def foo(path):
    _, _, files = next(os.walk(path))
    print(files)
    
files = foo(r'C:\Users') 
files[1]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nergeia
Solution 2 DollarAkshay