简体   繁体   中英

consolidated contents of all txt files into one- Python

I'm trying to consolidate all the result.txt file contents inside result folder and generating "Result_STD.txt" file out of it. But before writing to a file I want to add a str(GenerateFile) once but currently for every file append that string is getting added. Can anyone please suggest me how to add that string only once in a file?

def createOutput(self,STD):
    directory = "/result"
    read_files = glob.glob(directory + "/" + "*_result.txt")
    with open(directory + "/" + "Result_" + STD + ".txt", "wb") as outfile:
        for f in read_files:
            with open(f, "rb") as infile:
                data = infile.read()
                new_data = '{"GenerateFile":'+ data +  '}'
                print(new_data)
=================================================================
                
Current Output:

GenerateFile:{
    "Message": "CREATED", 
    "Result": "DONE"
}
GenerateFile:{
    "Message": "CREATED", 
    "Result": "DONE"
}

==============================================================
                
expected output:

GenerateFile:{
    "Message": "CREATED", 
    "Result": "DONE"
},
{
    "Message": "CREATED", 
    "Result": "DONE"
}

Does this do what you need it to do?

If so, all I did was move the new_data string initial assignment of GenerateFile: out of the for f in read_files: loop and append to it inside the loop, then print the output at the end of the loop.

def createOutput(self,STD):
    directory = "/result"
    read_files = glob.glob(directory + "/" + "*_result.txt")
    with open(directory + "/" + "Result_" + STD + ".txt", "wb") as outfile:
        new_data = "GenerateFile:"
        for f in read_files:
            with open(f, "rb") as infile:
                data = infile.read()
                new_data = new_data + " {" + data + "}, "
        print(new_data)

You might need to remove the last , before print(new_data) if it's a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM