Search substring in all text files in a directorysteemCreated with Sketch.

in hive-107130 •  5 years ago 

The following code searches a specific substring in all 'txt' file in a directory.

import os
import time
directory = 'D:/Python/file1/'

for filename in os.listdir(directory):
    filesize = os.stat(filename).st_size
    if (filesize>60000):
        continue
    # print(filename)
    
    with open(filename, 'rb') as f:
        lines = f.readlines()
        for line in lines:
            tempstr = str(line)
            le = len(tempstr)
            #print(tempstr)
            findresults=tempstr.find("binance") 
            #print(findresults)
            # time.sleep(5)
            if (findresults!=-1):
                print(filename)
                print(tempstr)
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!