lundi 16 novembre 2020

this code was supposed to look which files have this string in them but it only works when the string is 1 letter length

This is supposed to look in every readable file in the current directory and subdirectories for a certain string and list the result in a file but I have this issue:

For example, if I type "a" it works fine, but if I try multiple letters like "ad" or something it shows nothing.

What am I missing?

import os

look_for = input("type your string: ")

rootdir = os.getcwd()
list_of_files = []

for subdir, dirs, files in os.walk(rootdir):
    for file_name in files:
        file_path = subdir + os.sep + file_name
        print(file_path)
        try:
            with open(file_path, "r") as f:
                file_content = f.read()
                for line in file_content:
                    if look_for in line:
                        list_of_files.append(file_path + "\n")
                        break
                    else:
                        pass
        except UnicodeDecodeError:
            pass

result = open('search result.txt','w')
result.writelines(list_of_files)
result.close()

I'm suspecting these two lines

                for line in file_content:
                    if look_for in line:

Aucun commentaire:

Enregistrer un commentaire