。 由于目前的名录(由于该笔记本的目录缺席)与笔记不相同,你需要形成一条全面的道路。 http://docs.python.org/library/os.path.html#os.path.join“rel=“nofollow”>os.path.join:
data = shelve.open(os.path.join(path,newest), flag = "w")
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 use
filenames = [os.path.join(path,name) for name in os.listdir(path)]
newest = max(filenames, key = os.path.getmtime)
请注意,如果你这样做的话,那么ne 西
将是一个完整的路径名称,那么你就不需要os.path.join
in the shelve. open
line:
data = shelve.open(newest, flag = "w")
由此,除使用全部路标外,还有改变现有航标:
os.chdir(path)
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, calling os.chdir
in many places can make the code a bit spaghetti-like.
通过使用全方位的路径名称,你的工作是毫无疑问的。
If you wish to open each file:
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