简体   繁体   English

如何将多个变量存储在一个文件中,并从另一个文件中访问这些变量?

[英]How can I store many variables in one file, and access those variables from a different file?

I want to create a 'mini-database'. 我想创建一个'迷你数据库'。 I want to have one file with lots of variables, and be able to take those variables from the file, while also being able to add variables to the file? 我想要一个包含大量变量的文件,并且能够从文件中获取这些变量,同时还能够将变量添加到文件中吗? For example, lets suppose this is the 'mini-db': 例如,假设这是'mini-db':

hello = ['a', 'b', 'c']
world = ['d', 'e', 'f']
foo = ['g', 'h', 'i']

and from a different file, I would like to say something like: 从另一个文件,我想说:

print MiniDB.hello[0]

So basically access the variable. 所以基本上访问变量。 Also, I would need to write variables INTO the file. 另外,我需要在文件中写入变量INTO。 so something like this: 所以这样的事情:

MiniDB.bar = ['j', 'k', 'l']

How can I do this? 我怎样才能做到这一点?

shelve is the easiest way to do this. shelve是最简单的方法。 Mind the concurrency restrictions though. 但要注意并发限制。

This may not be what you are looking for, but this class allows storing program settings. 这可能不是您要找的,但此类允许存储程序设置。 You load it with default settings that represent the variables you need and embed dictionaries to generate namespaces. 您可以使用表示所需变量的默认设置加载它,并嵌入字典以生成名称空间。 It is not perfect, but tries to allow multiple database definitions to coexist with each other while ensuring data types do not change. 它并不完美,但尝试允许多个数据库定义相互共存,同时确保数据类型不会发生变化。 It has a limited field of usage but may act as the solution you require. 它的使用范围有限,但可以作为您需要的解决方案。

import copy
import pprint
import pickle

################################################################################

class _Interface:

    def __init__(self, default, database=None):
        self.__default = default
        if database is None:
            self.__database = copy.deepcopy(default)
        else:
            self.__database = database

    def __repr__(self):
        return pprint.pformat(self.__database)

    def __getattr__(self, name):
        attr = self.__default[name]
        if isinstance(attr, dict):
            return _Interface(attr, self.__database[name])
        raise AttributeError(name)

    def __setattr__(self, name, value):
        if name in {'_Interface__default', '_Interface__database'}:
            super().__setattr__(name, value)
        else:
            raise AttributeError(name)

    def __getitem__(self, name):
        item = self.__default[name]
        if isinstance(item, dict):
            raise KeyError(name)
        return self.__database[name]

    def __setitem__(self, name, value):
        item = self.__default[name]
        if isinstance(value, type(item)):
            self.__database[name] = value
        else:
            raise TypeError(type(value))

################################################################################

class Registry(_Interface):

    @property
    def __database(self):
        return self._Interface__database

    def load(self, path):
        with open(path, 'rb') as file:
            data = pickle.load(file)
        self.__merge(data, self.__database)

    @classmethod
    def __merge(cls, source, sink):
        for key, value in source.items():
            if key not in sink:
                sink[key] = value
            elif isinstance(value, type(sink[key])):
                if isinstance(value, dict):
                    cls.__merge(value, sink[key])
                else:
                    sink[key] = value

    def save(self, path):
        with open(path, 'wb') as file:
            pickle.dump(self.__database, file)

################################################################################

file1 = Registry({'hello': ['a', 'b', 'c'],
                  'world': ['d', 'e', 'f'],
                  'foo': ['g', 'h', 'i'],
                  'namespace': {'j': 0,
                                'k': 1,
                                'm': '2',
                                'n': '3'}})

file2 = Registry({'hello': ['a', 'b', 'c'],
                  'world': ['d', 'e', 'f'],
                  'foo': ['g', 'h', 'i'],
                  'namespace': {'j': '4',
                                'k': '5',
                                'm': '6',
                                'n': '7'},
                  'bar': []})

file1['hello'][0] = 'z'
file1.save('mini.db')
file2.load('mini.db')
file2['bar'].extend(['j', 'k', 'l'])

print(file2)
print(file2.namespace['k'])
print(file2.namespace['m'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 如何将多个变量存储在 .csv 文件的一列中,然后将这些变量读入列表 - Python - how to store multiple variables in one column of a .csv file and then read those variables into a list 在文件中存储许多变量 - Store many variables in a file 如何从 kv 文件中访问变量? - How can i to get access to variables from kv file? 无法将输入变量与文件中的变量进行比较 - Can't compare input variables to those from a file 如何在Python 3.x中从格式化的文本文件中识别和存储变量和数据? - How can one identify and store variables and data from a formatted text file in Python 3.x? 如何从 a.txt 文件中读取值并将它们保存到 python 中的不同变量中并访问它们? - How can I read values from a .txt-file and save them into different variables in python and get access to them? 如何从 a.txt 文件中提取数据并将其存储在 2 个单独的变量中? - How can i extract data from a .txt file and store it in 2 separate variables? 如何将变量存储在 function 中,以便我可以从不同的文件访问它 - How do I store a variable in a function so I can access it from a different file 在tkinter中,如何访问在另一个窗口中创建的变量? - In tkinter, how can I access variables created in one window in a different one? 如何读取文本文件并在python中存储为不同的变量 - How to read a text file and store as different variables in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM