Skip to content
Advertisement

Find files in a directory containing desired string in Python

I’m trying to find a string in files contained within a directory. I have a string like banana that I know that exists in a few of the files.

JavaScript

When the program runs, it just outputs string not found for every file. There are three files that contain the word banana, so the program isn’t working as it should. Why isn’t it finding the string in the files?

Advertisement

Answer

You are trying to search for string in filename, use open(filename, 'r').read():

JavaScript

We use user_input + os.sep + fname to get full path.
os.listdir gives files and directories names, so we use os.path.isfile to check for files.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement