Skip to content Skip to sidebar Skip to footer

Python Script To Search Directory For Certain File Type Then Append Their Contents Together

I am trying to make a python script that will search a directory for all files that end with a specific file extension called .math (basically a text file with numbers inside of th

Solution 1:

So not sure if you want to recursively search through a directory structure, or just list files in one directory. This should get you going.

import os

MATH_FILES = list()

defsingle_dir(name)
    global MATH_FILES
    names = [os.path.join(name, item) for item in os.listdir(name)]
        for name in names:
           if".math"in name and os.path.isfile(name):
               print("%s has .math in the name" % name)
               MATH_FILES.append(name)

defrecursive(name):
    global MATH_FILES
    if".math"in name and os.path.isfile(name):
        print("%s has .math in the name" % name)
        MATH_FILES.append(name)
    try:
        names = [os.path.join(name, item) for item in os.listdir(name)]
        for name in names:
            recurse(name)
    except:
        # Can't listdir() a file, so we expect this to except at the end of the tree.  passdefsum_file_contents():
    value = int()
    for file in MATH_FILES:
        value += int(open(file, "r").read().strip())
    return value

if __name__ == "__main__":
    # Choose implemntation here# recursive("<insert base path here>")# single_dir("<insert base path here>")print(sum_file_contents())

So some things.... Firstly in the if name conditional you need to choose either the single_dir or recursive function, and specify a path entry point (like /dir or C:\dir or whatever). The sum_file_contents will fail if there is anything other than an int in the file. Though your example states that is what you're looking for.

In conclusion, it would be good if you gave it a try before asking the question. I think the community at large isn't here to write code for you, but to help you if you get stuck. This is a super simple problem. if you google find files in a directory I bet there are literally dozens of answers, and that would at least give you a base of a code example. You could then say I can find my .math files like this, how do I sum them? You could probably find that answer simply as well. Please note I'm not trying to be rude with this paragraph.

Note: I did not test this code

Post a Comment for "Python Script To Search Directory For Certain File Type Then Append Their Contents Together"