0

我在文件夹 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")

它一直工作到最后一行,然后我收到一条错误消息:need "n" or "c" flag to run new db.

如果没有最后一行的标志,例如:data=shelve.open(newest),文件名到达 Python 代码的目录,而 db 中没有任何数据。

我需要能够将最新返回的文件名放在“”中,但不知道如何。

4

1 回答 1

4

newest只是文件名(例如test.db)。由于当前目录(默认情况下是运行脚本的目录)与 db 文件夹不同,因此您需要形成完整路径。你可以用os.path.join做到这一点:

data = shelve.open(os.path.join(path,newest), flag = "w") 

正如 Geoff Gerrietts 指出的那样,max(filenames)返回按字母顺序排在最后的文件名。也许这确实为您提供了您想要的文件。但是如果你想要最近修改时间的文件,那么你可以使用

filenames = [os.path.join(path,name) for name in os.listdir(path)]
newest = max(filenames, key = os.path.getmtime)

请注意,如果您这样做,那么newest将是一个完整的路径名,因此您不需要os.path.join在该shelve.open行中:

data = shelve.open(newest, flag = "w") 

顺便说一句,使用完整路径名的替代方法是更改​​当前目录:

os.chdir(path)

虽然这看起来更简单,但它也会使您的代码更难理解,因为读者必须跟踪当前工作目录是什么。如果只调用os.chdir一次,也许这并不难,但在复杂的脚本中,os.chdir在许多地方调用会使代码有点像意大利面条。

通过使用完整路径名,毫无疑问您在做什么。


如果要打开每个文件:

import os
import contextlib

filenames = [os.path.join(path,name) for name in os.listdir(path)]
for filename in filenames:
    with contextlib.closing(shelve.open(filename, flag = "w")) as data:
        # do stuff with data
        # ...
        # data.close() will be called for you when Python leaves this with-block
于 2012-01-13T14:46:57.057 回答