python open json file read write code example
Example 1: open json file python
import json
with open('data.txt') as json_file:
data = json.load(json_file)
Example 2: write json pythonb
import json
data = {}
data['people'] = []
data['people'].append({
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'
})
data['people'].append({
'name': 'Larry',
'website': 'google.com',
'from': 'Michigan'
})
data['people'].append({
'name': 'Tim',
'website': 'apple.com',
'from': 'Alabama'
})
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
Example 3: read file python
document = 'document.txt'
file = open(document, 'r')
# 'r' can be replaced with:
# 'w' to write
# 'a' to append (add to the end)
# 'w+' makes a new file if one does not already exist of that name
# 'a+' is the same as 'w+' but it appends if the file does exist
##go to beginning of document
file.seek(0)
##print all lines in document, except empty lines:
for i in file:
k = i.strip()
print k
##close the file after you are done
file.close()
##this can temporarily open a file:
with open(document) as ur:
for i in ur:
k = i.strip()
print k
Example 4: write json pythonb
import json
with open('data.txt') as json_file:
data = json.load(json_file)
for p in data['people']:
print('Name: ' + p['name'])
print('Website: ' + p['website'])
print('From: ' + p['from'])
print('')