Search code examples
pythonlist-comprehensionfilepath

List comprehension with multiple commands


I am creating output files for list of files. At the end of my routine, I would like to obtain a list of the output file names which I can achieve using the for block below. Is there a clean way to do such a thing using list comprehension or is this not a good time for comprehension?

import os

names = []
for file in f_list:
    base, ext = os.path.splitext(file)
    names.append(f"{base}_env{ext}")

The below works but if I can't get rid of the duplicated call of os.path.splitext, I'm not really excited by this.

[f"{os.path.splitext(file)[0]}_env{os.path.splitext(file)[1]}" for file in list]


Solution

  • You could use map:

    import os
    
    names = [f"{base}_env{ext}" for base,ext in map(os.path.splitext,f_list)]