如何在特定目录中打开Python shelve文件

3

我正在学习《Python编程快速上手》的第8章,尝试扩展Multiclipboard项目。以下是我的代码:

#! /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()

我已经将这个程序添加到我的路径中,并希望在任何工作目录中使用它。问题是shelve.open()会在当前工作目录下创建一个新文件。如何设置一个持久的目录?


使用绝对路径来指定 dbFile 是一个好的开始。目前看起来有些不对,因为它是相对于你所在的位置的一个相对路径,从 Users 开始,但实际上你可能想要的是 /Users - Nick T
2个回答

3
三年后,我又遇到了同样的问题。正如你所说。
shelfFile = shelve.open('fileName')

将书架文件保存到当前工作目录。根据脚本启动的方式,当前工作目录会发生变化,因此文件可能会被保存在不同的位置。

当然,您也可以说

shelfFile = shelve.open('C:\an\absolute\path')

但是如果原始脚本移动到另一个目录,这就有问题了。

因此,我想出了以下解决方案:

from pathlib import Path
shelfSavePath = Path(sys.argv[0]).parent / Path('filename')
shelfFile = shelve.open(fr'{shelfSavePath}')

这将会在Python脚本所在的同一目录下保存书架文件。
解释:
在Windows上,sys.argv[0]是脚本的完整路径名,可能看起来像这样:
C:\Users\path\to\script.py

请参考此处sys.argv的文档

在这个例子中

Path(sys.argv[0]).parent

会导致
C:\Users\path\to

我们可以使用 / 运算符,将 Path('filename') 添加到路径中。

这样会得到以下结果:

C:\Users\path\to\filename

始终将书架文件保存在与脚本相同的目录中,无论脚本位于哪个目录中。

请参阅pathlib文档


1
你的

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

将变成类似于'Users/dustin/Documents/repos/python/mcbdb',因此如果您从/Users/dustin/运行它,它将指向/Users/dustin/Users/dustin/Documents/repos/python/mcbdb,这可能不是您想要的。

如果您使用绝对路径,例如以/X:\(依赖于操作系统)为根的路径,将保留该“特定目录”。

我建议使用~os.path.expanduser来获取用户的主目录:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接