Search code examples
pythondictionarydata-transfer

How do you transfer the information of a dictionary from 1 python file to another and then back?


So here's the rundown of what I'm trying to do. It's long but I'm trying to be as specific as possible.

I am making a text adventure game with python. The problem was that the file got too big and I needed to create sister files for the different definitions because the editing started to get sluggish.

for the main file. When I run the main file, it grabs the definition just fine. But the sister file spits an error that it can't read the needed dictionary in the code. So I tried to just copy the dictionaries from the main file to the sister file. It works, but since the stats of everything in the dictionaries don't transfer from file to file and back, I tried this.

file 1:

import os,sys,ast
from file2 import *
player = {'name' : 'player',
          'hp' : 10}
enemy = {'name' : 'enemy2',
          'damage' : 5}
attack()

file 2:

import os,sys,ast
player = {'name' : 'player',
          'hp' : 10}
enemy = {'name' : 'enemy2',
          'damage' : 5}
with open("file1.py") as f:
    data = f.read(player)
    dictionary = ast.literal_eval(data)

def attack():
    player['hp'] = player['hp'] - enemy['damage']

I keep getting this error:

TypeError: argument should be integer or None, not 'dict'

But when I try to convert it to an integer:

File 2:

import os,sys,ast
enemy1 = {'name' : enemy1,
          'damage' : 10}
enemy2 = {'name' : enemy2,
          'damage' : 5}
with open('file.py') as f:
    data = f.read(int(str(player)))
    dictionary = ast.literal_eval(data)

def attack():
    player['hp'] = player['hp'] - enemy['damage']

I get:

ValueError: invalid literal for int() with base 10: '{}'

Because of the non-integer values.

I am trying to only load the one specific dictionary to the file, not all the rest of them at once. The reason I can't just have all of the exact dictionaries in the 2 files is that the definitions change the values in the dictionaries. Note that I am very limited in my knowledge and am mostly self taught through myself, sites like this and geeks for geeks.

I hope that this explanation of my problem covers what I'm trying to ask.


Solution

  • Edit

    Like the commenters suggest, rewrite your attack function to accept arguments instead of using globals.

    # File 2
    def attack(player, enemy):
        player['hp'] = player['hp'] - enemy['damage']
    
    # File 1
    …
    attack(player, enemy)