動態變量調用
背景
在讀寫json文件時,需要同時讀取多個json文件並處理,如果內嵌到循環中,每次讀取大大增加運行時間,寫多個讀寫操作又太傻瓜,希望能一次創建多個變量並對應讀取
具體操作
- 創建多個動態變量
# 創建動態變量函數
create_variable = locals()
for i in range(len(all_files)):
#create_variable['json_file_name_%i'%i]
root = '/home/flyingbird/Documents/reid_competition/combine_results/all_submission_files'
path = os.path.join(root, all_files[i])
with open(path, 'r') as json_file:
# 根據函數名創建並讀取
create_variable['json_file_name_%i'%i] = json.load(json_file)
- 調用變量
for num in range(len(all_files)):
# 調用上面生成的json文件
local_variable = create_variable.get('json_file_name_'+str(num))
# 根據文件讀取對應的信息
key_num_list.append(local_variable[key][j])
總結
使用動態變量兩步走,先調用local()函數,然後在賦予不同的變量名,最後利用變量的get屬性來調用變量
# 創建
create_variable = local()
# 賦值
for i in range(10):
create_variable['json_file_name_%i'%i] = i
# 調用
print(create_varibale['json_file_name_%i'%i]
json文件讀寫
和file文件讀寫類似,使用with open() as f:
#讀取
with open('read_path','r') as json_max:
# 後者讀取到前者
json_dict_max = json.load(json_max)
#寫入
with open('save_path', 'w') as ans:
# 前者保存到後者
json.dump(json_dict_ans, ans)