Search code examples
pythondatabaseshelve

How can I open a python shelve file in a specific directory


I am working on Ch. 8 of "Automate the Boring Stuff With Python", trying to extend the Multiclipboard project. Here is my code:

#! /usr/bin/env python3

# mcb.pyw saves and loads pieces of text to the clipboard
# Usage:        save <keyword> - Saves clipboard to keyword.
#               <keyword> - Loads keyword to the clipboard.
#               list - Loads all keywords to clipboard.
#               delete <keyword> - Deletes keyword from shelve.

import sys, shelve, pyperclip, os

# open shelve file
dbFile = os.path.join('Users', 'dustin', 'Documents', 'repos', 'python', 'mcbdb')
shelfFile = shelve.open(dbFile)


# Save clipboard content
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
   shelfFile[sys.argv[2]]= pyperclip.paste()

# Delete choosen content
elif len(sys.argv) == 3 and sys.argv[1].lower() == 'delete':
        if sys.argv[2] in list(shelfFile.keys()):
            del shelfFile[sys.argv[2]]
            print('"' + sys.argv[2] + '" has been deleted.')
        else:
            print('"' + sys.argv[2] + '" not found.')
elif len(sys.argv) == 2:
    # List keywords
    if sys.argv[1].lower() == 'list':
        print('\nAvailable keywords:\n')
        keywords = list(shelfFile.keys())
        for key in sorted(keywords):
            print(key)
    # Load content         
    elif sys.argv[1] in shelfFile:
        pyperclip.copy(shelfFile[sys.argv[1]])
    else:
        # Print usage error
        print('Usage:\n1. save <keyword>\n2. <keyword>\n' +
                '3. list\n4. delete <keyword>')
        sys.exit()

# close shelve file
shelfFile.close()

I have added this program to my path and would like to use it from whatever directory I am currently working in. The problem is that shelve.open() creates a new file in the current working directory. How can I have one persistent directory?


Solution

  • Your

    dbFile = os.path.join('Users', 'dustin', 'Documents', 'repos', 'python', 'mcbdb')
    

    will turn into something like 'Users/dustin/Documents/repos/python/mcbdb' so if you run it from /Users/dustin/ it'll point to /Users/dustin/Users/dustin/Documents/repos/python/mcbdb which is probably not what you want.

    If you use an absolute path, something rooted with either / or X:\ (OS-dependent) will keep that "specific directory".

    I might recommend something else though, get the user's home directory using ~ and os.path.expanduser:

    dbFile = os.path.expanduser('~/.mcbdb')