Heim  >  Fragen und Antworten  >  Hauptteil

Wie gehe ich mit einer Datei-Nichtexistenz-Ausnahme in Python3 beim Öffnen um?

with open('data.json', 'r') as f:
     self.cfg = json.load(f)

Das obige Code-Snippet kann data.json lesen,

Die Frage ist: Was soll ich tun, wenn data.json nicht existiert?

Ich habe bei Google gesucht und die meisten davon gefunden. Leider ist mein Englisch nicht sehr gut. Vielleicht habe ich etwas übersehen

Meine Erwartung ist:

Wenn data.json nicht existiert, erstellen und schreiben Sie die Standardparameter im Json-Format.

阿神阿神2662 Tage vor1037

Antworte allen(2)Ich werde antworten

  • 我想大声告诉你

    我想大声告诉你2017-07-05 10:36:57

    fn = input('输入文件名: ')
    try:
        with open(fn, 'r') as f:
            pass
    except IOError:
        file = open(fn, 'w')
    

    Antwort
    0
  • 给我你的怀抱

    给我你的怀抱2017-07-05 10:36:57

    import os
    import json
    
    name = 'data.json'
    if not(os.path.exists(name) and os.path.isfile(name)):
        with open(name, 'w') as f:
            f.write('["如果data.json不存在,便创建并写入Json格式的默认参数。"]')
            
    with open(name, 'r') as f:
        cfg = json.load(f)
    
        
    print(cfg)

    Antwort
    0
  • StornierenAntwort