【问题标题】:Shelve Database in Absolute Path在绝对路径中搁置数据库
【发布时间】:2017-07-17 05:39:31
【问题描述】:

在 Python 3.6 中,我试图在当前用户的主目录中创建一个名为 test.db 的数据库。目前,我正在使用home = os.path.expanduser("~") 获取该目录(在导入os 之后)。我的问题是,当我运行s = shelve.open(home + "/test") 时,它会在/path/to/current/python/file/Users/USERNAME/test.db 中创建文件。有没有办法通过绝对路径搁置数据库,例如/Users/USERNAME/test.db?另外,我可以让它跨平台吗? Windows 需要shelve.open(home + "\test") 而Mac/Linux 需要shelve.open(home + "/test")?谢谢。

【问题讨论】:

  • 为什么投反对票?
  • 我没有投反对票,但我认为这里应该有一个演示脚本。您的代码应该可以工作。我不知道'/path/to/python/file`是什么......它是你的python脚本的路径......你不在那个目录中吗?但是一个带有少量印刷品的简短脚本会使这一点更加清晰。

标签: python directory absolute-path shelve python-3.6


【解决方案1】:

要使其跨平台,请使用os.path.join() 加入路径

import os, shelve
path = os.path.join(os.path.expanduser("~"), 'test')
shelve.open(path)

【讨论】:

  • 如果我输入test.db,它会生成一个名为test.db.db的文件。
  • docs.python.org/3/library/shelve.html 上提到“文件可能会被低级库添加后缀”。这发生在我的 Linux 上,但没有发生在 Mac 上。最好不要提供扩展名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多