使用python shelve跨平台

发布于 2024-12-24 20:53:01 字数 886 浏览 5 评论 0原文

我希望得到关于 Python 中的书架/数据库的一些建议。

问题:我在 mac 上创建了一个数据库,我想在 windows 7 上使用它。我使用 Python 3.2、MacOS 10.7 和 win 7。

当我在 mac 上打开并保存我的书架时,一切都很好。我得到一个扩展名为“.db”的文件。在我的 windows-python 上它无法被识别。不过,我可以在电脑上创建一个新数据库并获取带有“.bak、dat、.dir”扩展名的文件。

我猜测电脑上的 python 没有与我的 mac-python 使用相同的底层数据库?

我不确定这里哪种方法是正确的,但也许我可以:

更改我的系统使用的默认数据库? 找出我的 mac-python 使用哪个数据库并将其添加到电脑上? 改变我存储数据的方式?

速度不是问题,数据大小只有几兆字节,并且访问频率不高。

希望在那里找到帮助。提前致谢 - 非常感谢任何帮助。

/Esben

我在做什么:

Import shelve
db = shelve.open('mydb')
entries = db['list']
db.close

这非常简单,我在 mac 上有一个名为“mydb.db”的工作数据库文件,但是当我尝试在 pc-python 上打开它时,我得到:

Traceback(最近一次调用最后) : 文件“/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/dbm/init.py”,第107行,其中db f = io.open(文件名 + ".pag", "rb") IOError: [Errno 2] 没有这样的文件或目录: 'mydb.pag'

I am hoping for a little advice on shelves/databases in Python.

Problem: I have a database created on the mac, that I want to use on windows 7. I use Python 3.2, MacOS 10.7, and win 7.

When I open and save my shelve on the mac all is good and well. I get a file with a ".db" extension. On my windows-python it is not recognized. I can however create a new db on the pc and get files with ".bak, dat, .dir" extensions.

I am guessing that the python on the pc does not have the same underlying database that my mac-python uses?

I am not sure which is the correct approach here, but maybe I could:

Change the default-db that my systems uses?
Find out which db my mac-python uses and add that on the pc?
Change the way I store my data all together?

Speed is not an issue, the datasize is a few megabytes, and it's not accessed very often.

Hope to find a helping hand out there. Thanks in advance - any help is much appreciated.

/Esben

What I am doing:

Import shelve
db = shelve.open('mydb')
entries = db['list']
db.close

It's pretty straight forward, I have a working db-file called "mydb.db" on the mac but when I try to open it on the pc-python i get:

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/dbm/init.py", line 107, in whichdb
f = io.open(filename + ".pag", "rb")
IOError: [Errno 2] No such file or directory: 'mydb.pag'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

感性 2024-12-31 20:53:01

感谢你的回复!

我似乎不太容易强迫 python 中的架子使用特定的数据库,但是 pickles 的工作方式就像一个魅力。至少从 mac os -> windows 7。

所以简短的回答:如果你想要便携性,不要使用架子,直接使用泡菜。

/埃斯本

Thank you for your reply!

I seems that shelves in python are not easily forced to use a specific db, however pickles works like a charm. At least from mac os -> windows 7.

So short answer: If you want portability, don't use shelves, use pickles directly.

/Esben

笙痞 2024-12-31 20:53:01

sqlite3模块是一个跨平台模块,甚至受到许多其他语言和工具的支持。

pickle模块比较简单,而且是跨平台的。您给它一个对象,它会将其转储到文件中。没有像 sqlite 这样的表或行。

sqlite3 module is a cross platform module that is even supported by many other languages and tools.

pickle module is simpler, but also cross platform. You give it an object and it dumps it to a file. No tables or rows like sqlite.

倾城泪 2024-12-31 20:53:01

我遇到了同样的问题,并实现了一个基于字典的类,该类支持从磁盘加载和写入字典的内容。

from pathlib import Path
import pickle


class DiskDict(dict):
    def __init__(self, sync_path: Path):
        self.path = sync_path

        if self.path.exists():
            with open(self.path, "rb") as file:
                tmp_dct = pickle.load(file)
                super().update(tmp_dct)
                print(f"loaded DiskDict with {len(tmp_dct)} items from {self.path}")

    def sync_to_disk(self):
        with open(self.path, "wb") as file:
            tmp_dct = super().copy()
            pickle.dump(tmp_dct, file)
            print(f"saved DiskDict with {len(tmp_dct)} items to {self.path}")

I ran into the same issue and implemented a dict-based class that supports loading and writing the contents of the dict from and to disk.

from pathlib import Path
import pickle


class DiskDict(dict):
    def __init__(self, sync_path: Path):
        self.path = sync_path

        if self.path.exists():
            with open(self.path, "rb") as file:
                tmp_dct = pickle.load(file)
                super().update(tmp_dct)
                print(f"loaded DiskDict with {len(tmp_dct)} items from {self.path}")

    def sync_to_disk(self):
        with open(self.path, "wb") as file:
            tmp_dct = super().copy()
            pickle.dump(tmp_dct, file)
            print(f"saved DiskDict with {len(tmp_dct)} items to {self.path}")
毁梦 2024-12-31 20:53:01

您可以尝试使用pysos,它是一个轻量级的搁置替代方案,也是跨平台的。

使用 pip 安装:pip install pysos

示例用法:

import pysos

db = pysos.Dict('myfile.db')
db['hello'] = 'persistence!'
db.close()

优点还在于所有内容都包含在这个单个文件 myfile.db 中,因此您可以轻松地复制它。

You might try using pysos, it's a lightweight shelve alternative that is also cross platform.

Install using pip: pip install pysos

Example usage:

import pysos

db = pysos.Dict('myfile.db')
db['hello'] = 'persistence!'
db.close()

The advantage is also that everything is contained in this single file myfile.db so you can easely just copy it around.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文