Writing a dict to txt file and reading it back?
Have you tried the json module? JSON format is very similar to python dictionary. And it's human readable/writable:
>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))
This code dumps to a text file
$ cat text.txt
{"two": 2, "one": 1}
Also you can load from a JSON file:
>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}
Your code is almost right! You are right, you are just missing one step. When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.
The error message you saw was because self.whip
was a string, not a dictionary. So you need to convert the string to a dictionary.
Example
Here is the simplest way: feed the string into eval()
. Like so:
def reading(self):
s = open('deed.txt', 'r').read()
self.whip = eval(s)
You can do it in one line, but I think it looks messy this way:
def reading(self):
self.whip = eval(open('deed.txt', 'r').read())
But eval()
is sometimes not recommended. The problem is that eval()
will evaluate any string, and if someone tricked you into running a really tricky string, something bad might happen. In this case, you are just running eval()
on your own file, so it should be okay.
But because eval()
is useful, someone made an alternative to it that is safer. This is called literal_eval
and you get it from a Python module called ast
.
import ast
def reading(self):
s = open('deed.txt', 'r').read()
self.whip = ast.literal_eval(s)
ast.literal_eval()
will only evaluate strings that turn into the basic Python types, so there is no way that a tricky string can do something bad on your computer.
EDIT
Actually, best practice in Python is to use a with
statement to make sure the file gets properly closed. Rewriting the above to use a with
statement:
import ast
def reading(self):
with open('deed.txt', 'r') as f:
s = f.read()
self.whip = ast.literal_eval(s)
In the most popular Python, known as "CPython", you usually don't need the with
statement as the built-in "garbage collection" features will figure out that you are done with the file and will close it for you. But other Python implementations, like "Jython" (Python for the Java VM) or "PyPy" (a really cool experimental system with just-in-time code optimization) might not figure out to close the file for you. It's good to get in the habit of using with
, and I think it makes the code pretty easy to understand.
To store Python objects in files, use the pickle
module:
import pickle
a = {
'a': 1,
'b': 2
}
with open('file.txt', 'wb') as handle:
pickle.dump(a, handle)
with open('file.txt', 'rb') as handle:
b = pickle.loads(handle.read())
print a == b # True
Notice that I never set b = a
, but instead pickled a
to a file and then unpickled it into b
.
As for your error:
self.whip = open('deed.txt', 'r').read()
self.whip
was a dictionary object. deed.txt
contains text, so when you load the contents of deed.txt
into self.whip
, self.whip
becomes the string representation of itself.
You'd probably want to evaluate the string back into a Python object:
self.whip = eval(open('deed.txt', 'r').read())
Notice how eval
sounds like evil
. That's intentional. Use the pickle
module instead.
Hi there is a way to write and read the dictionary to file you can turn your dictionary to JSON format and read and write quickly just do this :
To write your date:
import json
your_dictionary = {"some_date" : "date"}
f = open('destFile.txt', 'w+')
f.write(json.dumps(your_dictionary))
and to read your data:
import json
f = open('destFile.txt', 'r')
your_dictionary = json.loads(f.read())
I created my own functions which work really nicely:
def writeDict(dict, filename, sep):
with open(filename, "a") as f:
for i in dict.keys():
f.write(i + " " + sep.join([str(x) for x in dict[i]]) + "\n")
It will store the keyname first, followed by all values. Note that in this case my dict contains integers so that's why it converts to int
. This is most likely the part you need to change for your situation.
def readDict(filename, sep):
with open(filename, "r") as f:
dict = {}
for line in f:
values = line.split(sep)
dict[values[0]] = {int(x) for x in values[1:len(values)]}
return(dict)