Home > front end >  List is empty when appending when using recursion
List is empty when appending when using recursion

Time:06-29

I have two functions. The first one is used to get a list of paths to text files, and the second one is used to iterate over this list of paths and then check if they include the word password. But because of the Try Except statement in the second function, I had to use recursion to make it continue running unless there's another way if possible to provide below. My problem is that the list returned in the second function is empty why and how to fix it?

    def search_txt():
    """Function to search the C:\\ for .txt files -> then add them (including full path to file) to a list."""
    list_of_txt = []
    for dir_path, sub_dir, files in os.walk("C:\\"):
        """Method 1 -> checks the end of the file name (could be used for specific extensions)"""
        for file in files:
            if file.endswith(".txt"):
                list_of_txt.append(os.path.join(dir_path, file))
    return list_of_txt


def search_pass_file(list_of_files: list):
    """Function to iterate over each text file, searching if the word "password" is included -> Returns the text
    file's path """
    list_of_pass = []
    if len(list_of_files) != 0:
        for i in range(len(list_of_files)):
            file = list_of_files.pop()
            try:
                with open(file, encoding="utf8") as f:
                    for line in f.readlines():
                        if "password" in line:
                            list_of_pass.append(file)
            except UnicodeDecodeError:
                return search_pass_file(list_of_files)
            except PermissionError:
                return search_pass_file(list_of_files)
    else:
        return list_of_pass


if __name__ == '__main__':
    myList = search_txt()
    print(search_pass_file(myList))

CodePudding user response:

You're returning list_of_pass only if len(list_of_files) == 0 (it's in the else block). Your return statement should occur after the loop (which should be a while one btw)

You can except several errors in one line by putting them in parenthesis: except (UnicodeDecodeError, PermissionError) of except all exceptions (for instance, you're not handling FileNotFoundError).

I'd reduce your function to:

def search_pass_file(list_of_files: list):
    """Function to iterate over each text file, searching if the word "password" is included -> Returns the text
    file's path """
    list_of_pass = []
    while list_of_files:
        file = list_of_files.pop()
        try:
            with open(file, encoding="utf8") as f:
                for line in f.readlines():
                    if "password" in line:
                        list_of_pass.append(file)
                        break
        except Exception:
            list_of_pass  = search_pass_file(list_of_files)
    return list_of_pass

Edit: also in your except block, you should append the returned value of the recursive function to list_of_pass otherwise you'll lose the files found after the error occurs.

  • Related