9

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.

1
  • Why python? Ever heard of grep? Commented Nov 16, 2015 at 20:16

3 Answers 3

17
import os

keyword = 'file'
for fname in os.listdir('directory/with/files'):
    if keyword in fname:
        print(fname, "has the keyword")
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.