shenk shenk - 6 months ago 35
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
append_id
function?

Answer

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.

Comments