Python: get a complete file name based on a partial file name

Viewed 7308

In a directory, there are two files that share most of their names:

my_file_0_1.txt
my_file_word_0_1.txt

I would like to open my_file_0_1.txt

I need to avoid specifying the exact filename, and instead need to search the directory for a filename that matches the partial string my_file_0.

From this answer here, and this one, I tried the following:

import numpy as np
import os, fnmatch, glob

def find(pattern, path):
        result = []
        for root, dirs, files in os.walk(path):
                for name in files:
                        if fnmatch.fnmatch(name, pattern):
                                result.append(os.path.join(root, name))
        return result

if __name__=='__main__':

        #filename=find('my_file_0*.txt', '/path/to/file')
        #print filename
        print glob.glob('my_file_0' + '*' + '.txt')

Neither of these would print the actual filename, for me to read in later using np.loadtxt.

How can I find and store the name of a file, based on the result of a string match?

3 Answers

I just developed the approach below and was doing a search to see if there was a better way and came across your question. I think you may like this approach. I needed pretty much the same thing you are asking for and came up with this clean one liner using list comprehension and a sure expectation that there would only be one file name matching my criteria. I modified my code to match your question.

import os


file_name = [n for n in os.listdir("C:/Your/Path") if 'my_file_0' in n][0]
print(file)

Now, if this is in a looping / repeated call situation, you can modify as below:

for i in range(1, 4):
    file = [n for n in os.listdir("C:/Your/Path") if f'my_file_{i}' in n][0]
    print(file)

or, probably more practically ...

def get_file_name_with_number(num):
    file = [n for n in os.listdir("C:/Your/Path") if f'my_file_{num}' in n][0]
    return file


print(get_file_name_with_number(0))
Related