Python 代码位于一个目录中,数据库文件位于另一目录中。如何打开数据库和进程?
我在文件夹 A 中有一个 db 文件目录。我的 python 代码从另一个地方运行。
当我运行以下代码时:
path = 'xxx' # path to file directory
filenames = os.listdir(path) # list the directory file names
#pprint.pprint(filenames) # print names
newest=max(filenames)
print newest # print most recent file name
# would like to open this file and write to it
data=shelve.open(newest, flag="w")
它一直运行到最后一行,然后我收到一条错误消息:需要“n”或“c”标志来运行新数据库
。
如果没有最后一行中的标志,例如:data=shelve.open(newest)
,则文件名到达 Python 代码的目录时,数据库中没有任何数据。
我需要能够将最新返回的文件名放入“”中,但不知道如何。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
newest
只是文件名(例如test.db
)。由于当前目录(默认情况下运行脚本的目录)与 db 文件夹不同,因此您需要形成完整路径。您可以使用 os.path.join 来做到这一点:正如 Geoff Gerrietts 指出的那样,
max(filenames)
返回按字母顺序排列在最后的文件名。也许这确实给了你你想要的文件。但是如果您想要具有最近修改时间的文件,那么您可以使用注意,如果您这样做,那么
newest
将是完整路径名,因此您不需要shelve.open
行中的 >os.path.join:顺便说一句,使用完整路径名的替代方法是更改当前目录:
虽然这看起来更简单,但它也可以使你的代码更难理解,因为读者必须跟踪当前工作目录是什么。
如果只调用 os.chdir 一次,也许这并不难,但在复杂的脚本中,在很多地方调用 os.chdir 可能会使代码有点像意大利面条。
通过使用完整路径名,您将毫无疑问地知道您正在做什么。
如果您想打开每个文件:
newest
is just the filename (e.g.test.db
). Since the current directory (by default the directory from which the script was run) is not the same as the db folder, you need to form a full path. You can do that with os.path.join:As Geoff Gerrietts points out,
max(filenames)
returns the filename that comes last in alphabetical order. Perhaps that does give you the file you desire. But if you want the file with the most recent modification time, then you could useNote that if you do it this way, then
newest
will be a full path name, so you would then not needos.path.join
in theshelve.open
line:By the way, an alternative to using full path names is to change the current directory:
Although this looks simpler, it can also make your code harder to comprehend, since the reader has to keep track of what the current working directory is.
Perhaps this is not hard if you only call
os.chdir
once, but in a complicated script, callingos.chdir
in many places can make the code a bit spaghetti-like.By using full path names there is no question about what you are doing.
If you wish to open each file: