newest只是文件名(例如test.db)。由于当前目录(默认情况下是运行脚本的目录)与db文件夹不同,因此需要形成一个完整的路径。您可以使用os.path.join:data = shelve.open(os.path.join(path,newest), flag = "w")
正如Geoff Gerrietts指出的,max(filenames)返回按字母顺序排在最后的文件名。也许这确实给了你想要的文件。但是如果您希望文件具有最新的修改时间,则可以使用
^{pr2}$
请注意,如果您这样做,那么newest将是一个完整的路径名,因此您不需要在shelve.open行中使用os.path.join: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