idealistikz
idealistikz

Reputation: 1267

How do I iterate through a series of filenames if the previous option does not exist in Python?

Suppose I have a directory of files and each filename begins with the date in the format, 'YYYYMMDD.' Given a filename, how do I check if it exists and, if it doesn't, check the filename with the subsequent date?

I have the following, but it only checks if the filename exists.

try:
   with open('filename') as f: pass
except IOError as e:
   print 'The file does not exist.'

If there is only one file in the list, I want to exit. If there are several files in the list, I want to check the following date.

Upvotes: 0

Views: 91

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56634

import glob
import bisect

filenames = sorted(glob.glob('*'))

def get_file_name_prev(fname):
    idx = bisect.bisect_right(filenames, fname)-1
    if idx < 0:
        raise ValueError('no preceding filename is available')
    else:
        return filenames[idx]

def get_file_name_next(fname):
    idx = bisect.bisect_left(filenames, fname)
    if idx >= len(filenames):
        raise ValueError('no subsequent filename is available')
    else:
        return filenames[idx]

Edit: @J.F. Sebastian: it is easy to test.

filenames = ['b', 'd']

get_file_name_prev('c')  # => returns 'b'
get_file_name_next('c')  # => returns 'd'

If he wants the next file name, then he needs bisect.bisect_left.

Upvotes: 3

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73588

To check if a path is an existing file:

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

more follows....

Upvotes: 0

Related Questions