reading, modifying and writing json file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: reading, modifying and writing json file (/thread-10777.html) |
reading, modifying and writing json file - metalray - Jun-06-2018 Hi Python Experts, I am trying to open a json file, modify the content and write it to a different directory. The code runs but nothing is really happening. I am not sure what should come first, the dump or the misc save. Is the dump a save as well? from scipy import ndimage, misc import numpy as np import os import cv2 import json def main(): outPath='C:/..../' path='C:/...../data_aug_test/' # iterate through the names of contents of the folder for file_path in os.listdir(path): #create the full input path and read the file input_path = os.path.join(path, file_path) if file_path.endswith('.jpg'): print('jpeg process') else: #.json print('else json handling') with open(input_path, 'r') as f: data = json.load(f) data['id'] = 134 # <--- modify value. #write file then save jsonsavepath = os.path.join(outPath, 'flipped_'+file_path) misc.imsave(jsonsavepath, f) with open(input_path, 'w') as f: json.dump(data, f, indent=4) if __name__ == '__main__': main() RE: reading, modifying and writing json file - Larz60+ - Jun-06-2018 don't forget that: for file_path in os.listdir(path):will get you everything in path, including directories Can't run your code as is, so don't know if this is an issue. It could be in the future, so still not a good idea. if running python 3.5 or newer, you can use pathlib (untested code): >>> from pathlib import Path >>> path Path(C:/Users/HOLLEYP/Downloads/TSS_DonkeyCarChallenge/tubs/tubs_cleaned/data/data_aug_test/) >>> files = [x for x in home.iterdir() if x.is_file()] >>> for file_path in files: ... do stuff here >>> RE: reading, modifying and writing json file - metalray - Jun-06-2018 OK. Thanks. Got it. |