Python script to search directory for certain file type then append their contents together

南笙酒味 提交于 2019-12-24 08:05:30

问题


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 them).

How would I approach doing so?

Imagine I have files hello.math, hello2.math, and goodbye.math

Lets say hello.math has 10, hello2.math has 3 and goodbye.math has 0.

i would want the script to search for all of the .math files in the current directory then sum them up.


回答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()

def single_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)

def recursive(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.  
        pass

def sum_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



来源:https://stackoverflow.com/questions/51661506/python-script-to-search-directory-for-certain-file-type-then-append-their-conten

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!