2017-06-16 3 views
-1

ich schreibe ein Skript in Python tun eine Weile wahr cicle, wie kann ich mein Skript nehmen Sie die gleiche Datei abc123.json für jeden cicle und ändern einige Variablen drin?wie man python schreiben json lesen und schreiben gleiche Datei für jeden cicle

+1

Bitte geben Sie etwas Code, den Sie bereits versucht haben – Slam

+0

Ich weiß nicht, was "während True Cicle" bedeutet, aber Sie möchten wahrscheinlich die JSON-Datei in ein Python-Objekt laden, alle Ihre Änderungen vornehmen, und dann dump Ergebnis zurück zu JSON. –

Antwort

0

Wenn ich Ihre Frage richtig verstehe, möchten Sie eine Datei namens abc123.json irgendwo auf einer lokalen Festplatte lesen, die über Pfad erreichbar ist und einen Wert für einen Schlüssel (oder mehr) für diese json-Datei ändern, dann re -Schreib es. Ich bin ein Beispiel von Code einfügen ich in der Hoffnung, eine Weile her, verwendet es hilft

import json 
from collections import OrderedDict 
from os import path 

def change_json(file_location, data): 
    with open(file_location, 'r+') as json_file: 
     # I use OrderedDict to keep the same order of key/values in the source file 
     json_from_file = json.load(json_file, object_pairs_hook=OrderedDict) 
     for key in json_from_file: 
      # make modifications here 
      json_from_file[key] = data[key] 
     print(json_from_file) 
     # rewind to top of the file 
     json_file.seek(0) 
     # sort_keys keeps the same order of the dict keys to put back to the file 
     json.dump(json_from_file, json_file, indent=4, sort_keys=False) 
     # just in case your new data is smaller than the older 
     json_file.truncate() 

# File name 
file_to_change = 'abc123.json' 
# File Path (if file is not in script's current working directory. Note the windows style of paths 
path_to_file = 'C:\\test' 

# here we build the full file path 
file_full_path = path.join(path_to_file, file_to_change) 

#Simple json that matches what I want to change in the file 
json_data = {'key1': 'value 1'} 
while 1: 
    change_json(file_full_path, json_data) 
    # let's check if we changed that value now 
    with open(file_full_path, 'r') as f: 
     if 'value 1' in json.load(f)['key1']: 
      print('yay') 
      break 
     else: 
      print('nay') 
      # do some other stuff 

Beobachtung: der Code oben geht davon aus, dass sowohl die Dateien und die json_data die gleichen Schlüssel zu teilen. Wenn dies nicht der Fall ist, muss Ihre Funktion herausfinden, wie Schlüssel zwischen Datenstrukturen zu finden sind.

Verwandte Themen