construct an unknown url from known information
Question: I'm trying to create a python script... basically...

I have a url to some site

    
    
    url = "http://www.somesite.com/foo/bar/"
    

Files on server:

    
    
    1-123j.jpg
    2-123.jpg
    3-123d.jpg
    4-1594ss.jpg
    ...
    ...
    45000-457li.jpg
    

I know the beginning of the filename (a number) and the file extension (.jpg),
but there is a part of the name that is unknown(some random string that I
don't know)...

How do I construct a url to "2-123.jpg" if I don't know the 123 part of the
name?

What I know...

    
    
    correctURL = "http://www.somesite.com/foo/bar/2-*****.jpg"
    

the correct url would be:

    
    
    "http://www.somesite.com/foo/bar/2-123.jpg"
    

Is this even possible?


Answer: Aside from mentioning that it is quite hard to guess random urls, I'll go
ahead and post an answer with some assumptions that might lead to a valid
solution. The disclaimer here is that I don't know what your possibilities are
with regard to server access and such, and hence will make several assumptions
on filename formats or directory contents and the like. If you have no server
access, then your solution doesn't really have a real answer to it, I guess.

So, here goes. First, get a list of filenames on the server:

    
    
    import os
    with open('filenames.txt') as f:
        files = os.listdir('.') # Assuming you are in the correct dir
        f.write('\n'.join(files))
    

This gives you all available files on the server. Generate this as often as
you want, automate it, preferably with copying it to your web server so that
you are always up to date.

Then, on your web server, do something like this:

    
    
    files = open('filenames.txt').read().split('\n')
    d = {}
    for f in files:
        s = f.split('-', 1)
        d[s[0]] = s[-1]
    

Your dictionary now contains the key/value pairs needed to construct the
correct filename. You can do this periodically, storing the result somewhere
for faster access, or just run it whenever you need to construct an url.

The final step is to construct the url, like so:

    
    
    n = 2 # The number you got somewhere
    fmt = 'http://www.somesite.com/foo/bar/{}-{}'
    url = fmt.format(n, d[n])
    

