2016-11-15 78 views
2

我有三个简短的JSON文本文件。我想将它们与Python结合起来,并且就其工作原理而言,在正确的位置创建一个输出文件,在最后一行我有一个逗号,我想用}替换它。我已经想出了这样的代码:替换文本文件中的最后一个字符(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

您正在编写所有文件,然后重新加载以更改最后一行。虽然这个改变只会在内存中,而不是在文件本身。更好的方法是避免首先编写额外的,。例如:

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

这首先写入除最后一个文件以外的所有逗号,然后单独写入最后一个文件。您可能还想检查单个文件的情况。

+0

作品perferctly,谢谢你! – totoczko

相关问题