How to Save file names and their directories path in a text file using Python
Question: I am trying to find a string that is contained in files under a directory.
Then make it to store it's file names and directories under a new text file or
something. I got upto where it is going through a directory and finding a
string, then printing a result. But not sure of the next step.

Please help, I'm completely new to coding and python.

    
    
    import glob, os
    
    
    
    #Open a source as a file and assign it as source
    source = open('target.txt').read()
    filedirectories = []
    
    #locating the source file and printing the directories.
    os.chdir("/Users/a1003584/desktop")
    for root, dirs, files in os.walk(".", topdown=True):
        for name in files:
            print(os.path.join(root, name))
            if source in open(os.path.join(root, name)).read():
                print 'treasure found.'
    


Answer: Don't do a string comparison if your looking for a dictionary. Instead use the
json module. Like this.

    
    
    import json
    import os
    
    filesFound = []
    
    def searchDir(dirName):
        for name in os.listdir(dirName):
            # If it is a file.
            if os.isfile(dirName+name):
                try:
                    fileCon = json.load(dirName+name)
                except:
                    print("None json file.")
                if "KeySearchedFor" in fileCon:
                    filesFound.append(dirName+name)
            # If it is a directory.
            else:
                searchDir(dirName+name+'/')
    
    # Change this to the directory your looking in. 
    searchDir("~/Desktop")
    open("~/Desktop/OutFile.txt",'w').write(filesFound)
    

