In Python 3.6 I am trying to but a database called test.db
in the current user's home directory. Currently, I am getting that directory with home = os.path.expanduser("~")
(after importing os
). My problem is that when I run s = shelve.open(home + "/test")
it creates the file in /path/to/current/python/file/Users/USERNAME/test.db
. Is there a way to shelve a database by an absolute path, e.g. /Users/USERNAME/test.db
? Also, can I make it cross platform; Windows would require shelve.open(home + "\test")
and Mac/Linux would require shelve.open(home + "/test")
? Thanks.
Asked
Active
Viewed 503 times
-1

Nobody
- 133
- 1
- 13
-
Why the downvote? – Nobody Feb 26 '17 at 17:41
-
I didn't downvote, but I think there should be a demo script here. Your code should work. I don't know what '/path/to/python/file` is... is it the path to your python script... and you aren't in that directory? But a short script with a few prints would make this more clear. – tdelaney Feb 26 '17 at 17:54
1 Answers
1
To make it cross platform, use os.path.join()
to join paths
import os, shelve
path = os.path.join(os.path.expanduser("~"), 'test')
shelve.open(path)

Taku
- 31,927
- 11
- 74
- 85
-
1
-
On https://docs.python.org/3/library/shelve.html it mentions "file may get suffix added by low-level library". This happened to me on Linux but not Mac. Best not to provide an extension. – jrc May 25 '19 at 23:01