문제는 프로세스가 파일의 "로드 된"JSON 데이터를 절대 통과하지 못하므로 그 이유를 이해하지 못한다는 것입니다. 매번 새 파일을 만드는 과정을 거칩니다. 코드와 매우 몇 가지 문제가 있습니다JSON 파일이 비어 있지 않고 temp 폴더의 파일에서 JSON 데이터를 올바르게로드하는지 확인하는 방법은 무엇입니까?
import argparse
import os
import tempfile
import json
storage = argparse.ArgumentParser()
storage.add_argument("--key", help="input key's name")
storage.add_argument("--val", help="value of key", default=None)
args = storage.parse_args()
storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')
with open(storage_path,'r') as f:
if f.seek(2) is not 2:
data_base = json.load(f)
print('loaded that: ',data_base)
else:
f.close()
print('each time I am creating the new one')
with open(storage_path,'w') as f:
data_base = {}
f.close()
if data_base.get(args.key, 'Not found') == 'Not found':
if args.val is not None:
data_base.setdefault(args.key, args.val)
with open(storage_path, 'w') as f:
json.dump(data_base, f)
print('dumped this: ',data_base)
당신은 파이썬 2.7.x,'file.seek를 사용하는 경우()'리턴'None'. 또한 평등 테스트에 아이덴티티 테스트 ('is')를 사용하지 마십시오. 어쨌든'2 is 2' (CPython에서는 실제로 작동 할 것입니다. 그러나 구현 세부 사항으로 인한 사고입니다) –
@brunodesthuilliers 나는 파이썬 3.6.x를 사용하고있다. –