Writing a Dict to Txt File and Reading It Back

Writing a dict to txt file and reading it back?

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.

How to output a dictionary to a text file?

You can simply replace {v} with {v[0]} {v[1]}:

output = open("output.txt", "w")
for k, v in dict3.items():
output.writelines(f'{k} {v[0]} {v[1]}\n')

Writing a dictionary to a text file?

First of all you are opening file in read mode and trying to write into it.
Consult - IO modes python

Secondly, you can only write a string or bytes to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.

import json

# as requested in comment
exDict = {'exDict': exDict}

with open('file.txt', 'w') as file:
file.write(json.dumps(exDict)) # use `json.loads` to do the reverse

In case of serialization

import cPickle as pickle

with open('file.txt', 'w') as file:
file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse

For python 3.x pickle package import would be different

import _pickle as pickle

Write dictionary to text file with newline

The str() method for a dict return it as a single line print, so if you want to format your output, iterate over the dict and write in the file the way you want.

test_dict = {'A': '1', 'B': '2', 'C': '3'}
f = open("dict.txt", "w")
f.write("{\n")
for k in test_dict.keys():
f.write("'{}':'{}'\n".format(k, test_dict[k]))
f.write("}")
f.close()

How to write dictionary to a text file properly

You are adding the string conversion of your dictionary onto the file. Each time you run your program, the a+ flag tells it to append as a string.

You can fix this by using a json format–like you imported:

import json

mydic = {}

# Read existing data
with open('cd.json', 'r') as jsonFile:
mydic = json.load(jsonFile)

# Get usernames and passwords
for i in range(3):
uname = input("enter uname\n")
pwd = input("enter pwd\n")

mydic[uname] = pwd

print(mydic)

# Write new values
with open('cd.json', 'w') as jsonFile:
json.dump(mydic, jsonFile, indent=4, sort_keys=True)

First we read the existing values, then we run through the code you wrote to get usernames and passwords, and finally, we save all the data to a json file.



Related Topics



Leave a reply



Submit