totoczko totoczko - 19 days ago 8
JSON Question

Replace last character in text file (python)

I have three short JSON text files. I want to combine them with Python, and as far as it works and creates an output file with everything on the right place, on the last line I have a comma, and I would like to replace it with

}
. I have came up with such a code:

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(",","")


but it doesn't replace the last line. Could somebody help me? I am new to Python and I can't find the solution by myself.

Answer

You are writing all of the files, and then loading it back in to change the last line. The change though will only be in memory, not in the file itself. The better approach would be to avoid writing the extra , in the first place. For example:

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])

This first writes all but the last file with the extra comma, and then writes the last file seperately. You might also want to check for the case of a single file.

Comments