Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a filename that contains a given string

Tags:

python

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.

like image 592
Brutos Avatar asked Nov 16 '15 20:11

Brutos


People also ask

How do I search for a file name in a string?

You can use “grep” command to search string in files. Alternatively, You can also also use the "find " command to display files with specific string. Hope this answer help you.

How do I find all files containing specific text?

Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.

How do I find a file with a specific name?

Finding files by name is probably the most common use of the find command. To find a file by its name, use the -name option followed by the name of the file you are searching for. The command above will match “Document. pdf”, “DOCUMENT.

How do I use grep to find a filename?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


2 Answers

import os

keyword = 'file'
for fname in os.listdir('directory/with/files'):
    if keyword in fname:
        print(fname, "has the keyword")
like image 198
inspectorG4dget Avatar answered Oct 15 '22 19:10

inspectorG4dget


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
like image 35
Peter Wood Avatar answered Oct 15 '22 17:10

Peter Wood