Brutos
Brutos

Reputation: 119

How to find a filename that contains a given string

I'm attempting to look for a keyword of a text file within a directory then find out the whole name of the file using Python.

Let this keyword be 'file', but this text file in the directory is called 'newfile'.

I'm trying to find out the name of the whole file in order to be able to open it.

Upvotes: 9

Views: 33886

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

You could use fnmatch. From the documentation:

This example will print all file names in the current directory with the extension .txt:

import fnmatch
import os

for filename in os.listdir('.'):
    if fnmatch.fnmatch(filename, '*.txt'):
        print filename

From your example you would want fnmatch(filename, '*file*').

e.g:

>>> from fnmatch import fnmatch
>>> fnmatch('newfile', '*file*')
True

>>> fnmatch('newfoal', '*file*')
False

Upvotes: 2

ppflrs
ppflrs

Reputation: 311

Using grep you can locate file containing the word you are looking for.

grep -r 'word' FOLDER

-r indicates grep to look for 'word' in all the files of FOLDER

Upvotes: -1

inspectorG4dget
inspectorG4dget

Reputation: 113955

import os

keyword = 'file'
for fname in os.listdir('directory/with/files'):
    if keyword in fname:
        print(fname, "has the keyword")

Upvotes: 17

Related Questions