shenk shenk - 1 year ago 127
Python Question

How to add an id to filename before extension?

I have a filename: name.ext

I want to do the following:

name + id + '.' + ext for name, ext in filename.split()

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

Here is what I have so far:

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('.'))

but it treats it as a generator expression, which is not my intended result.

What would be the correct way to write the

Answer Source

To do it in one line you can try:

def append_it(filename):
    return "{0}_{2}.{1}".format(*filename.rsplit('.', 1) + [generate_id()])

It's not very readable though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download