Home > Software engineering >  How to write key and value to file with dict in it on python?
How to write key and value to file with dict in it on python?

Time:08-04

I started to learn python recently, and I need your help guys.

For example: I have file named Data.py and there is a dictionary d={} in there.

Also, I have file called Main.py. I want to add key with values in dictionary, save it and then try to print it in Main.py file. Is that possible?

UPD:

I think i better use JSON, but another question is how to do that with json? I have 0 experience working with JSON. I need to somehow put dictionary in there and then parse to get information, add key and values and save file.

CodePudding user response:

You can either use a json file or even a function with a return statement.

Make sure both the files are in the same directory (folder) and rename Data.py to get_data.py and then write a new function.

def transfer():
    global d

    return d

d = {}

And in your Main.py:

from get_data import *
print(transfer())

CodePudding user response:

Here's a way to implement JSON file

#Data.py
import json

d = {'total': 0}
f = open('data.txt', 'w')
while True:
    x = input('Enter number: ')
    if x.lower() == 'q':
        f.close()
        break
    elif x.isdigit():
        d['total']  = float(x)
        f.seek(0, 0)
        f.write(json.dumps(d))

Output #Data.py

Enter number:  12
Enter number:  13
Enter number:  q

And in another code

#Main.py

import json

f = open('data.txt', 'r').read()
d = json.loads(f)
print(d['total'])
f.close()

Output #Main.py

25.0
  • Related