I have a directory of db files in folder A. My python code runs from another place.
When I run the following code:
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")
It works up until the last line, then I get an error which says: need "n" or "c" flag to run new db
.
Without the flag in the last line eg: data=shelve.open(newest)
, the file name arrives in the Python code's directory without any data in the db.
I need to be able to put the filename returned by newest in " ", but don't know how.
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: