4

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?

StatsSorceress
  • 3,019
  • 7
  • 41
  • 82
  • 2
    `glob.glob` is the way to go, I think. `glob.glob('my_file_0*.txt')` returns a list of file names, use indexing to retrieve the file you need. – vaultah Jul 30 '17 at 20:50
  • Agreed. `glob.glob` is a wrapper around `fnmatch`, but it's a wrapper that does exactly what you want to do right here. – Adam Smith Jul 30 '17 at 20:51
  • @StatsSorceress make sure you have this files in the directory you run you script as `glob` should work – Dmitry Senkovich Jul 30 '17 at 20:52

3 Answers3

4

glob.glob() needs a path to be efficient, if you are running the script in another directory, it will not find what you expect. (you can check the current directory with os.getcwd())

It should work with the line below :

print glob.glob('path/to/search/my_file_0' + '*.txt')

or

print glob.glob(r'C:\path\to\search\my_file_0' + '*.txt') # for windows
PRMoureu
  • 12,817
  • 6
  • 38
  • 48
1

A solution using os.listdir()

Could you not also use the os module to search through os.listdir()? So for instance:

import os

partialFileName = "my_file_0"

for f in os.listdir():
    if partialFileName = f[:len(partialFileName)]:
        print(f)
Community
  • 1
  • 1
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

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))
Thom Ives
  • 3,642
  • 3
  • 30
  • 29