HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Generate out_filename from input_filename and suffix

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
suffixout_filenameinput_filenamegenerateandfrom

Problem

I do a lot of steps of processing over an input_file. To avoid having to think of an output_filename at every step, I created the following name generation function:

def generate_out_file(in_file, suffix='out'):
    body_str = in_file.strip('./')
    flag = '.' in body_str
    _list = body_str.split('.')
    body_list = _list[:-1] if flag else [in_file]
    extension = _list[-1] if flag else 'txt'
    out_file = '.'.join(body_list + [suffix, extension])
    if in_file.startswith('./'):
        out_file = './' + out_file
    if in_file.startswith('../'):
        out_file = '../' + out_file
    return out_file


It looks very huge for me. Can you review my code and help me to improve it?

Solution

You can dramatically simplify the function by using the os.path.splitext() instead:

import os

def generate_out_file(in_file, suffix='out'):
    """Appends '.out' to an input filename."""
    filepath, file_extension = os.path.splitext(in_file)
    return filepath + "." + suffix + file_extension


Demo:

$ ipython3 -i test.py
In [1]: generate_out_file("./file.txt")  # file in a current directory
Out[1]: './file.out.txt'

In [2]: generate_out_file("/usr/lib/file.txt")  # path to a file
Out[2]: '/usr/lib/file.out.txt'

In [3]: generate_out_file("file.txt")  # just a file name
Out[3]: 'file.out.txt'

In [4]: generate_out_file("file")  # no extension
Out[4]: 'file.out'

In [5]: generate_out_file("/usr/lib/file")  # no extension with a path
Out[5]: '/usr/lib/file.out'

Code Snippets

import os


def generate_out_file(in_file, suffix='out'):
    """Appends '.out' to an input filename."""
    filepath, file_extension = os.path.splitext(in_file)
    return filepath + "." + suffix + file_extension
$ ipython3 -i test.py
In [1]: generate_out_file("./file.txt")  # file in a current directory
Out[1]: './file.out.txt'

In [2]: generate_out_file("/usr/lib/file.txt")  # path to a file
Out[2]: '/usr/lib/file.out.txt'

In [3]: generate_out_file("file.txt")  # just a file name
Out[3]: 'file.out.txt'

In [4]: generate_out_file("file")  # no extension
Out[4]: 'file.out'

In [5]: generate_out_file("/usr/lib/file")  # no extension with a path
Out[5]: '/usr/lib/file.out'

Context

StackExchange Code Review Q#157889, answer score: 5

Revisions (0)

No revisions yet.