How to add an id to filename before extension?
<p>I have a filename: name.ext </p>

<p>I want to do the following:</p>

<pre><code>name + id + '.' + ext for name, ext in filename.split()
</code></pre>

<p>or find a better way to take a filename and add a random 7 character string to the end before the extension.</p>

<p>Here is what I have so far:</p>

<pre><code>def generate_id(size=7, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def append_id(filename):
    return (name + '_' + generate_id() + '.' + ext for name, ext in filename.split('.'))
</code></pre>

<p>but it treats it as a generator expression, which is not my intended result.</p>

<p>What would be the correct way to write the <code>append_id</code> function?</p>