How to add an id to filename before extension?

To do it in one line you can try:

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

It’s not very readable, though.

Most language implementations provide functions to deal with file names, and Python is no exception. You should use os.path.splitext:

def append_id(filename):
  return "{0}_{2}{1}".format(*os.path.splitext(filename) + (generate_id(),))

Note that the second version needs two additional modifications:

  • splitext returns a tuple not a list, so we need to wrap the result of generate_id with a tuple
  • splitext retains the dot, so you need to remove it from the format string

Still, I wouldn’t struggle to have a oneliner here – see the next answer for more readable solutions.

Python 3.4 introduces pathlib module and you can use it like this:

from pathlib import Path

def append_id(filename):
  p = Path(filename)
  return "{0}_{2}{1}".format(p.stem, p.suffix, generate_id())

This will work for filenames without preceding path only. For files with paths use this:

from pathlib import Path

def append_id(filename):
  p = Path(filename)
  return "{0}_{2}{1}".format(Path.joinpath(p.parent, p.stem), p.suffix, generate_id())

In Python 3.9 there is also with_stem, which might be the most suitable choice for this case.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)