Posts

Showing posts from October, 2016

update a JSON file by using Python?

You did not save the changed data at all. You have to first load, then modify, and only then save. It is not possible to modify JSON files in-place. with open ( 'my_file.json' , 'r' ) as f : json_data = json . load ( f ) json_data [ 'b' ] = "9" with open ( 'my_file.json' , 'w' ) as f f . write ( json . dumps ( json_data )) You may also do this: with open ( 'my_file.json' , 'r+' ) as f : json_data = json . load ( f ) json_data [ 'b' ] = "9" f . seek ( 0 ) f . write ( json . dumps ( json_data )) f . truncate () If you want to make it safe, you first write the new data into a temporary file in the same folder, and then rename the temporary file onto the original file. That way you will not lose any data even if something happens in between. If you come to think of that, JSON data is very difficult to change in-place, as the data length is not fixed, and the...

Exception Hierarchy

BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError | +-- AssertionError | +-- AttributeError | +-- EnvironmentError | | +-- IOError | | +-- OSError | | +-- WindowsError (Windows) | | +-- VMSError (VMS) | +-- EOFError | +-- ImportError | +-- LookupError | | +-- IndexError | | +-- KeyError | +-- MemoryError | +-- NameError | | +-- UnboundLocalError | +-- ReferenceError | +-- RuntimeError | | +-- NotImplementedError | +-- SyntaxError | | +-- IndentationError | | +-- TabError | +-- SystemError | ...

How do I get the directory in Python?

import os print ( "Path at terminal when executing this file" ) print (os.getcwd() + " \n " ) print ( "This file path, relative to os.getcwd()" ) print (__file__ + " \n " ) print ( "This file full path (following symlinks)" ) full_path = os.path.realpath(__file__) print (full_path + " \n " ) print ( "This file directory and name" ) path, filename = os.path.split(full_path) print (path + ' --> ' + filename + " \n " ) print ( "This file directory only" ) print (os.path.dirname(full_path)) print ( 'get the root file path' ) import os.path print (os.path.abspath(os.path.join(os.getcwd(), os.pardir)))

Append and Update json object python

import json with open ( "knowledge.json" , 'r' ) as f: data = json.load(f) data[ "worksbuddy.com" ][ "google.com" ][ "input" ].append([ 3 , 4 ]) data[ "worksbuddy.com" ][ "google.com" ][ "output" ].append( 6 ) with open ( 'knowledge.json' , 'w' ) as f: f.write(json.dumps(data)) print (data)