2016-11-15 311 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