2015-02-03 1 views
0

작은 스크립트를 작성하여 json dict을 생성하고 사용중인 json 파일의 끝에 삽입하십시오. json 파일을 열어 수정하는 방식과 관련해서 뭔가 진행되고 있다고 생각합니다. "}이]"가 Python : IOError : [Errno 2] 그런 파일이나 디렉토리가 없습니다 : -하지만 파일이 있습니다.

  • 그것은 파일을 기록 그것은
  • 그것은 JSON 파일을 엽니 다 raw_input을에서 JSON의 딕셔너리를 생성하고 라인을 읽고

    1. , 마이너스가 포함 된 마지막 두 : 여기

      은 광주 과학 기술원의 마지막 두 줄이없이 돌아왔다.

      JSON_PATH = "~/Desktop/python/custconn.json" 
      
      def main(): 
          # CLI Input 
          group_in = raw_input("Group: ") 
          name_in = raw_input("Name: ") 
          nick_in = raw_input("Nick: ") 
          host_in = raw_input("Host: ") 
          user_in = raw_input("User: ") 
          sshport_in = raw_input("SSH Port: ") 
          httpport_in = raw_input("HTTP Port: ") 
      
          # New server to add 
          jdict = { 
           "group": group_in, 
           "name": name_in, 
           "nick": nick_in, 
           "host": host_in, 
           "user": user_in, 
           "sshport": sshport_in, 
           "httpport": httpport_in 
          } 
      
          # Remove trailing "} ]" in json file 
          with open(JSON_PATH, mode='r') as wf: 
           lines = wf.readlines() 
           lines = lines[:-2] 
           wf.close() 
          # Write change 
          with open(JSON_PATH, mode='w') as wf: 
           wf.writelines([item for item in lines]) 
           wf.close() 
          # Write new server entry at the end 
          with open(JSON_PATH, mode='a') as nf: 
           nf.write(" },\n") 
           nf.write(" {}\n".format(json.dumps(jdict, indent=4))) 
           nf.write("]\n") 
           nf.close() 
      

      오류 :

      Traceback (most recent call last): 
          File "./jbuild.py", line 47, in <module> 
          main() 
          File "./jbuild.py", line 30, in main 
          with open(JSON_PATH, mode='w') as wf: 
      IOError: [Errno 2] No such file or directory: '~/Desktop/python/custconn.json' 
      

      이 파일은 그 존재 않습니다

    2. 다음에,

    코드 "]}"폐쇄와 새로운 DICT 항목을 기록합니다 경로, 그러나 ..

  • +1

    [어디서나 개방 (파일)]의 중복 가능성 (http://stackoverflow.com/questions/12184161/openfile-from-anywhere) – vaultah

    답변

    1

    당신이 필요 os.path.expanduser :

    Unix 및 Windows에서는 ~ 또는 ~ user의 초기 구성 요소가있는 사용자의 홈 디렉터리로 대체 된 인수를 반환합니다.

    import os 
    os.path.expanduser(path) 
    
    +1

    흥미 downvotes 나는 downvote 그냥 때문에 받았다고 생각 –

    +0

    그것은 불완전한 대답이었다. 약간의보고만으로 나는 전체 솔루션을 찾았습니다. 감사합니다. 홈 = 확장 사용자 ("~") JSON_PATH = home + "/Desktop/python/custconn.json" – oorahduc

    +0

    @pythduc. 단지'os.expanduser (JSON_PATH)'가 작동해야합니다. –

    관련 문제