2017-12-01 7 views
1

문제는 프로세스가 파일의 "로드 된"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) 
+0

당신은 파이썬 2.7.x,'file.seek를 사용하는 경우()'리턴'None'. 또한 평등 테스트에 아이덴티티 테스트 ('is')를 사용하지 마십시오. 어쨌든'2 is 2' (CPython에서는 실제로 작동 할 것입니다. 그러나 구현 세부 사항으로 인한 사고입니다) –

+0

@brunodesthuilliers 나는 파이썬 3.6.x를 사용하고있다. –

답변

1

, 즉

프로그램 파일이 존재하지 않는 경우 충돌 :

with open(storage_path,'r') as f: 

개방 storage_path을 쓰기 위해 실제로 쓰고 있지 아무것도 :

print('each time I am creating the new one') 
    with open(storage_path,'w') as f: 
     data_base = {} 
    f.close() 

사실 실제로 f.seek(2) == 2 일 경우, json.load(f)은 또한이 시점에서 파일 포인터를 3 번째 문자로 이동했기 때문에 후속 json.load()에서 전체 내용을 가져 오지 못하기 때문에 충돌이 발생합니다.

여기 AFAICT 작동합니다 고정 된 버전입니다 :

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

data_base = None 
if os.path.exists(storage_path): 
    with open(storage_path,'r') as f: 
     try: 
      data_base = json.load(f) 
      print('loaded that: ',data_base) 
     except Exception as e: 
      print("got %s on json.load()" % e) 

if data_base is None: 
    print('each time I am creating the new one') 
    data_base = {} 
    with open(storage_path,'w') as f: 
     json.dump(data_base, f) 

# don't prevent the user to set `"Not found" as value, if might 
# be a legitimate value. 
# NB : you don't check if `args.key` is actually set... maybe you should ? 

sentinel = object()  
if data_base.get(args.key, sentinel) is sentinel:   
    if args.val is not None: 
     data_base[args.key] = args.val 
     with open(storage_path, 'w') as f: 
      json.dump(data_base, f) 
      print('dumped this: ',data_base) 
+0

>>'args.key'가 실제로 설정되어 있는지 확인하지 않는다. 어쩌면해야 할까? 실제로 argparse가 나를 위해 그것을합니까? –

+0

@pure_true 아니, 그렇지 않습니다. 옵션은 글쎄, 선택 사항입니다. 명시 적으로 선택적으로 설정하지 않는 한 : https://docs.python.org/3/library/argparse.html#required –