Search code examples
pythonpython-3.xpython-os

Using Python search for a string in each file in a folder and subfolders


I have written some code for all files in a folder but I want to check for the string even in sub folders. Suggest me for sub folders

from os import listdir
path='D:\\PyScripts'
keywords=['version','navigate']
for file in listdir('D:\\PyScripts'):
with open('D:\\PyScripts\\'+ file,'r') as f:
    data=f.read()
    data=data.lower()
    valid_keys=list(map(counters,keywords))

    if valid_keys:
        ****Some logic*****

Solution

  • This is how it can be done. I tested using my folder files. Change it up for your needs.

    import os
    from os import walk
    path='D:\\files'
    keywords=['test','this']
    
    for root, dirs, files in walk(path):
        for name in files:            
            with open(os.path.join(root, name),'r') as f:
                data=f.read()
                data=data.lower()
    
                print(data)