How to Save a Dictionary to a File

How to save a dictionary into a file, keeping nice format?

You can use pprint for that:

import pprint
pprint.pformat(thedict)

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

Save/Load a Dictionary

Use pickle. This is part of the standard library, so you can just import it.

import pickle

pet_stats = {'name':"", 'int':1, 'bool':False}

def pet_save(pet):
with open(pet['name'] + '.pickle', 'wb') as f:
pickle.dump(pet, f, pickle.HIGHEST_PROTOCOL)

def digimon_load(pet_name):
with open(pet_name + '.pickle', 'rb') as f:
return pickle.load(f)

Pickle works on more data types than JSON, and automatically loads them as the right Python type. (There are ways to save more types with JSON, but it takes more work.) JSON (or XML) is better if you need the output to be human-readable, or need to share it with non-Python programs, but neither appears to be necessary for your use case. Pickle will be easiest.

If you need to see what's in the file, just load it using Python or

python -m pickle foo.pickle

instead of a text editor. (Only do this to pickle files from sources you trust, pickle is not at all secure against hacking.)

How to save a dictionary to a file with key values one per line?

You can so this is a couple of lines with a CounterDict and the csv module:

import csv
def makeFile(textSorted, newFile) :
from collections import Counter
with open(newFile, "w") as f:
wr = csv.writer(f,delimiter=":")
wr.writerows(Counter(textSorted).items())

Using two dictionaries is pointless if you just want to store the key/value pairs. A single Counter dict will get the count for all the words and csv.writerows will write each pair separated by a colon one pairing per line.

Python: Saving dictionary to .py file

1) use file.write:

file.write('this_dict = ')
json.dump(this_dict, dict_file)

2) use write + json.dumps, which returns a string with json:

file.write('this_dict = ' + json.dumps(this_dict)

3) just print it, or use repr

file.write('this_dict = ')
file.write(repr(this_dict))
# or:
# print(this_dict, file=file)

how to save a dictionary on a file and then load it(working with json and files) - python

You should be using json.dump() to write JSON back to the file. You also need to rewind so that you start writing at the beginning.

And after you write, you have to truncate it in case the new JSON is shorter than the original.

@bot.command()
async def register(exc):
with open("accounts.txt","r+") as f:
w=json.load(f)
w[exc.author.id]="some"
f.seek(0)
json.dump(f)
f.truncate()


Related Topics



Leave a reply



Submit