tags:

views:

93

answers:

2

I'm trying to make a program that checks an array to make sure there are four folders with partially same names.

So

For a date like 0103 (jan 3rd), there should be 0103-1, 0103-2, 0103-3, and 0103-4. Other folders are like 0107-1, 0107-2, 0107-3, 0107-4. How do I go about doing this? I thought about using glob.glob (python) and wildcards to make sure there are only four matches...but I don't like this method.

Any suggestions?

+3  A: 
import os

def myfunc(date, num):
    for x in range(1, num+1):
        filename = str(date) + "-" + str(x)
        if os.path.exists(filename):
            print(filename+" exists")
        else:
            print(filename+" does not exist")

myfunc('0102', 3);

0102-1 does not exist

0102-2 does not exist

0102-3 does not exist

Kevin
s/.exists/.isdir/
J.F. Sebastian
A: 

Here's a naive way to find the largest common leading substring given an array of strings:

>>> arr = ['0102-1', '0102-2', '0102-3']
>>> for i in reversed(range(len(arr[0]))):
...     for s in arr:
...         if not s.startswith(arr[0][:i+1]):
...            break
...     else:
...         break
... else:
...     if i == 0: i = -1
...
>>> arr[0][:i+1]
'0102-'
>>> i
4
J.F. Sebastian