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.
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.
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.
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.
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'.
import os
keyword = 'file'
for fname in os.listdir('directory/with/files'):
if keyword in fname:
print(fname, "has the keyword")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With