我有三个简短的JSON文本文件。我想将它们与Python结合起来,并且只要它工作并创建一个输出文件,其中所有内容都在正确的位置,在最后一行我有一个逗号,我想用}
替换它。我想出了这样的代码:
def join_json_file (file_name_list,output_file_name):
with open(output_file_name,"w") as file_out:
file_out.write('{')
for filename in file_name_list:
with open(filename) as infile:
file_out.write(infile.read()[1:-1] + ",")
with open(output_file_name,"r") as file_out:
lines = file_out.readlines()
print lines[-1]
lines[-1] = lines[-1].replace(",","")
但它并没有取代最后一行。有人能帮帮我吗?我是Python的新手,我无法自己找到解决方案。
答案 0 :(得分:0)
您正在编写所有文件,然后将其重新加载以更改最后一行。但更改只会在内存中,而不是在文件本身中。更好的方法是避免首先编写额外的,
。例如:
def join_json_file (file_name_list, output_file_name):
with open(output_file_name, "w") as file_out:
file_out.write('{')
for filename in file_name_list[:-1]:
with open(filename) as infile:
file_out.write(infile.read()[1:-1] + ",")
with open(file_name_list[-1]) as infile:
file_out.write(infile.read()[1:-1])
首先使用额外的逗号写入除最后一个文件以外的所有文件,然后单独写入最后一个文件。您可能还想检查单个文件的大小写。