[英]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.我正在尝试合并结果文件夹中的所有 result.txt 文件内容并从中生成“Result_STD.txt”文件。 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.但在写入文件之前,我想添加一个 str(GenerateFile) 一次,但目前为每个文件 append 添加该字符串。 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.如果是这样,我所做的就是将GenerateFile:
的new_data
字符串初始分配移出for f in read_files:
循环和 append 到循环内,然后在循环结束时打印 output 。
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.如果有问题,您可能需要在print(new_data)
之前删除最后一个,
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.