I have looked at other questions on SO like this one but they are too techy for me to understand (only been learning a few days).
I am making a phonebook and i am trying to save a dictionary like so,
numbers = {}
def save(a):
x = open("phonebook.txt", "w")
for l in a:
x.write(l, a[l])
x.close()
But i get error write() only takes 1 argument and obv im passing 2, so my question is how can i do this in a beginner freindly way and could you describe it in a non techy way.
Thanks a lot.
It's better to use json module for dumping/loading dictionary to/from a file:
>>> import json
>>> numbers = {'1': 2, '3': 4, '5': 6}
>>> with open('numbers.txt', 'w') as f:
... json.dump(numbers, f)
>>> with open('numbers.txt', 'r') as f:
... print json.load(f)
...
{u'1': 2, u'3': 4, u'5': 6}
While JSON is a good choice and is cross-language and supported by browsers, Python has its own serialization format called pickle that is much more flexible.
import pickle
data = {'Spam': 10, 'Eggs': 5, 'Bacon': 11}
with open('/tmp/data.pickle', 'w') as pfile:
pickle.dump(data, pfile)
with open('/tmp/data.pickle', 'r') as pfile:
read_data = pickle.load(pfile)
print(read_data)
Pickle is Python-specific, doesn't work with other languages, and be careful to never load pickle data from untrusted sources (such as over the web) as it's not considered "safe".
Pickle works for other data types too, including instances of your own classes.
You need to use the json module and JSONEncode your dict, then you can use the module to write the new object to file.
When you read the file, you need to JSONDecode to convert it back into a python dict.
>>> import json
>>> d = {1:1, 2:2, 3:3}
>>> d
{1: 1, 2: 2, 3: 3}
>>> json.JSONEncoder().encode(d)
'{"1": 1, "2": 2, "3": 3}'
>>> with open('phonebook.txt', 'w') as f:
f.write(json.JSONEncoder().encode(d))
>>> with open('phonebook.txt', 'r') as f:
print f.readlines()
['{"1": 1, "2": 2, "3": 3}']
Related
I have two json objects coming from a file. Those two objects make one record. They are of different length. I was using pandas.read_json(), but didnt work.
Here is an example:
input:
{"a":1,"b":2,"c":3}{"x":[100],"y":"123"}
expected output:
{
"a":1,
"b":2,
"c":3,
"x":[100],
"y":"123"
}
IIUC, You want to read two JSON and create a new JSON from them.
import json
new_json = {}
for json_file in ['js1.json', 'js2.json']:
with open(json_file) as f:
d = json.load(f)
new_json.update(d)
print(new_json)
# {'a': 1, 'b': 2, 'c': 3, 'x': [100], 'y': '123'}
# create a new json that contains two old json
res = json.dumps(new_json)
Update You can use ast.literal_eval, If two JSON in one file.
import json
import ast
# jss.json -> {"a":1,"b":2,"c":3}{"x":[100],"y":"123"}
new_json = {}
for json_file in ['jss.json']:
with open(json_file) as f:
jsons = f.read()
for js in jsons.split('}')[:-1]:
st = js+'}'
d = ast.literal_eval(st)
new_json.update(d)
print(new_json)
# {'a': 1, 'b': 2, 'c': 3, 'x': [100], 'y': '123'}
# create a new json that contains two old json
res = json.dumps(new_json)
I'm sure this is simple but my heads not with it today, I'm trying to output a JSON file in this format:
{"A": {"B": [1, 1, 1, 1, 1, 1]}}
My code so far is:
jsonobj = {"A":{"B":[]
},
}
var1 = 1
jsonobj["A"]["B"].append(dict(f=var1))
with open('data.json', 'w') as f:
json.dump(jsonobj, f)
print jsonobj
As you can guess its a mismatch of code from StackOverflow and outputting wrong,
{'A': {'B': [{'f': 1}]}}
Sure it's an easy one, Thanks in advance.
You need to do
jsonobj["A"]["B"].append(var1)
If it is like
var1 = [1,1,1,1]
jsonobj["A"]["B"].extend(var1)
I have a list like this:
d = [{string1:float1,string2: float2},{string1:float3,string2:float4},...]
I tried:
import json
with open("outputfile.txt","w") as f:
json.dump(d,f)
then all the content is in one line like:
[{string1:float1,string2: float2},{string1:float3,string2:float4},{string1:float5,string2:float6},...]
what I want is for each (key:valve) starts a newline,like
[{string1:float1,
string2:float2},
{string1:float3,
string2:float4},
...
endstring:endfloat}]
how can I do this ? or I can just replace every "," to ",\n"? The order does not matter much, but if possible, a "sorted" result will be appreciated.
As per https://docs.python.org/2.7/library/json.html:
json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': '))
should result in:
{
"4": 5,
"6": 7
}
Python 3.x solution is identical.
Note the use of dumps as opposed to dump.
Updated solution:
for dict in d:
with open("outputfile.txt","a") as f:
json.dump(dict, f)
f.write('\n')
or
for dict in d:
with open("outputfile.txt","a") as f:
json.dump(dict, f, indent=4)
I'm trying to pickle high scores and then print them.
In the actual program, score is acquired from a simple trivia game.
score = 10
name = input("Name: ")
scores = [name, score]
high_scores = open("high_scores.dat", "ab")
pickle.dump(scores, high_scores)
high_scores.close()
high_scoresR = open("high_scores.dat", "rb")
results = pickle.load(high_scoresR)
print(results)
high_scores.close()
The program prints only the first high score entered, it doesn't matter how many scores I try to dump to it. Example:
['Jason', 10]
I am guessing I don't understand something quite basic, so I would highly appreciate a informative and clear explanation.
You can use 'wb' mode to write multiple pickles to a file, and if you need to reopen it for one ore more additional dump, then you should use append mode ('a', not 'w'). Here I write multiple entries using 'wb', and then later add one entry using 'ab'.
>>> scores = dict(Travis=100, Polly=125, Guido=69)
>>> import pickle
>>> with open('scores.pkl', 'wb') as highscores:
... for name,score in scores.items():
... pickle.dump((name,score)), highscores)
...
>>> with open('scores.pkl', 'ab') as highscores:
... pickle.dump(scores, highscores)
...
>>> with open('scores.pkl', 'rb') as highscores:
... a = pickle.load(highscores)
... b = pickle.load(highscores)
... c = pickle.load(highscores)
... d = pickle.load(highscores)
...
>>> a
('Travis', 100)
>>> b
('Polly', 125)
>>> c
('Guido', 69)
>>> d
{'Polly': 125, 'Travis': 100, 'Guido': 69}
>>>
And if you have a lot of data, so that you are worried about being able to dump and/or load all of your items at once, then you can use (one of my packages) klepto, which enables you to store large pickled data to a file, directory, or database… where you can seamlessly access one entry at a time.
>>> import klepto
>>> store = klepto.archives.dir_archive('high', serialized=True)
>>> store.update(scores)
>>> store
dir_archive('high', {'Polly': 125, 'Guido': 69, 'Travis': 100}, cached=True)
>>> # dump all entries at once
>>> store.dump()
>>> # create a new empty archive proxy
>>> store2 = klepto.archives.dir_archive('high', serialized=True)
>>> store2
dir_archive('high', {}, cached=True)
>>> # load one entry, as opposed to loading all entries
>>> store2.load('Guido')
>>> store2
dir_archive('high', {'Guido': 69}, cached=True)
>>> store2['Guido']
69
>>> # load everything else
>>> store2.load()
>>> store2
dir_archive('high', {'Polly': 125, 'Guido': 69, 'Travis': 100}, cached=True)
>>>
You could read your file into a dictionary:
name = input('Enter name: ')
score = input('Enter score: ')
# write new entry to file
with open('highscores.txt', 'a') as f:
f.write(name + ':' + score + '\n')
# read file into dict
with open('highscores.txt', 'r') as f:
lines = f.read().splitlines()
scores = dict(line.split(':') for line in lines)
for key, value in scores.items():
print(key, value)
I didn't know you were trying to learn pickle, but maybe this helps someone else.
I just want to write dictionary values into text file line wise line.I can write whole dictionary in to the file using:
log_disk={}
log=open('log.txt','w')
log.write(str(log_disk))
log.close()
Any help will be appreciated.In addition I want to avoid those keys which have value 'Empty' while writing into the file.
Just loop over the values then:
with open('log.txt','w') as log:
for value in log_disk.values():
log.write('{}\n'.format(value))
Write data as JSON unformatted string
You may dump the data as JSON, without formatting JSON data it is written on one line.
Do not forget to append newline:
>>> import json
>>> data = {}
>>> with open(fname, "a") as f:
... json.dump(data, f)
... f.write("\n")
...
Try with another data:
>>> data = {"a": "aha", "b": "bebe"}
>>> with open(fname, "a") as f:
... json.dump(data, f)
... f.write("\n")
...
It does not have to be dictionary, lists are working too:
>>> data = range(10)
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> with open(fname, "a") as f:
... json.dump(data, f)
... f.write("\n")
...
Reading data line by line
>>> with open(fname) as f:
... for line in f:
... print json.loads(line)
...
{}
{u'a': u'aha', u'b': u'bebe'}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You just need to convert log_disk.values() to a list and you can write them directly
with open(filename) as openfile:
json.dump(list(log_disk.values()), file)