我創建了一個 python 代碼來打開多個檔案并編輯它們,最后分別保存每個檔案
第一個檔案沒問題,但之后,其他檔案的大小一個一個地增加。
import json
import os
from datetime import datetime
os.chdir('C:\\Users\\user1\\Desktop\\Test')
list_Files = []
date = datetime.now()
result = []
counter = 0
cnt = 0
for single_file in os.listdir('C:\\Users\\user1\\Desktop\\Test') :
list_Files.append(single_file)
print(single_file)
with open(single_file, encoding='utf-8') as fn:
for line in fn.readlines():
counter =1
result.append(json.loads(line))
cnt =1
print(cnt)
json_file = 'C:\\Users\\user1\\Desktop\\Out\\tst_' f"{str(single_file)}{cnt}"'.json'
with open(json_file, 'w') as outfile:
json.dump(result, outfile)
uj5u.com熱心網友回復:
在遍歷所有檔案之前初始化結果陣列。在回圈檔案時附加結果陣列,使這個陣列更長result.append(json.loads(line))。然后,在您的檔案回圈中,您將結果陣列寫入您的 json 檔案。因此,每個新的 json 檔案都會收到一個更長的結果陣列,因此檔案大小也會更大。
如果你在你的檔案回圈中初始化/重置你的結果陣列,你會很好。請參閱下面的示例代碼。
import json
import os
from datetime import datetime
os.chdir('C:\\Users\\user1\\Desktop\\Test')
list_Files = []
date = datetime.now()
# result = [] removed the results array here
counter = 0
cnt = 0
for single_file in os.listdir('C:\\Users\\user1\\Desktop\\Test') :
result = [] # initialize/reset the results array here
list_Files.append(single_file)
print(single_file)
with open(single_file, encoding='utf-8') as fn:
for line in fn.readlines():
counter =1
result.append(json.loads(line))
cnt =1
print(cnt)
json_file = 'C:\\Users\\user1\\Desktop\\Out\\tst_' f"{str(single_file)}{cnt}"'.json'
with open(json_file, 'w') as outfile:
json.dump(result, outfile)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/329729.html
上一篇:Python迭代排除型別不是bool、float、int或不是NoneType(TypeError:'NoneType'物件不可迭代)
