Reputation: 11
I am trying to find a file with a particular string (say 'xyz') as part of its name. That is, if the files in the directory have names
'abc def'
'ghi jkl'
'xyz mno'
'pqr asd'
Then I want to save the file name 'xyz mno' in a variable, for copying it to another directory.
Right now, I am using the following code to list out all the files in the particular directory :
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
So now, onlyfiles is a list with all the filenames. I just need to find the one that matches with my criterion. Maybe this is very easy, but I am pretty new to python and am not familiar with the language yet. Do help.
Upvotes: 1
Views: 1604
Reputation: 586
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f)) and 'xyz' in f]
Only a little change in third line of your code does the thing.
Upvotes: 1
Reputation: 1788
This way:
from os import listdir
from os.path import isfile, join
subString = "xyz"
mypath = "/tmp"
onlyGoodfiles = [f for f in listdir(mypath) if isfile(join(mypath, f)) and subString in f]
Upvotes: 1