StatsSorceress
StatsSorceress

Reputation: 3099

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

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?

Upvotes: 4

Views: 9001

Answers (3)

Thom Ives
Thom Ives

Reputation: 3969

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))

Upvotes: 0

Joe Iddon
Joe Iddon

Reputation: 20414

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)

Upvotes: 1

PRMoureu
PRMoureu

Reputation: 13327

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

Upvotes: 4

Related Questions