使用python架空跨平台

问题描述 投票:11回答:3

我希望能得到一点关于Python中的 shelvesdatabases的建议。

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

当我在Mac上打开并保存我的数据库时,一切都很好。我得到一个扩展名为".db "的文件。在我的windows-python上,它不被识别。然而,我可以在PC上创建一个新的数据库,并得到".bak, dat, .dir "扩展名的文件。

我猜测PC上的Python与我的Mac-python使用的底层数据库不一样?

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

改变我的系统使用的default-db? 找出我的mac-python使用的db然后添加到pc上? 改变我存储数据的方式?

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

希望能在外面找到一个帮手。先谢谢你--任何帮助都非常感激。

Esben

我正在做什么。

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

很简单,我在Mac上有一个叫 "mydb.db "的工作数据库文件 但当我试图在PC -python上打开它时,我得到的是:

回溯(最近一次调用): 文件 "LibraryFrameworksPython.frameworkVersions3.2libpython3.2dbm"。启动.py",第107行,其中db f = io.open(filename + ".pag", "rb")IOError.[Errno 2] No such file or directory: 'mydb.pag': [Errno 2] 没有这样的文件或目录:'mydb.pag' 。

python database cross-platform python-3.x shelve
3个回答
3
投票

谢谢你的回复!

我觉得Python中的架子不容易被强制使用一个特定的db,但是pickles就像一个魅力。至少从mac os -> windows 7。

所以简短的回答。如果你想要便携性,不要用 shelves,直接用 pickles。

埃斯本


1
投票

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

pickle模块更简单,但也是跨平台的。你给它一个对象,它就会把它转储到一个文件中。不像sqlite那样有表有行。


0
投票

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

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}")
© www.soinside.com 2019 - 2024. All rights reserved.