6
\$\begingroup\$

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?

200_success
146k22 gold badges190 silver badges478 bronze badges
asked Mar 16, 2017 at 4:46
\$\endgroup\$
1
  • \$\begingroup\$ if we change first line to body_str = os.path.basename(in_file), then last 4 lines can be replaces with out_file = '/'.join([os.path.dirname(in_file), out_file]) \$\endgroup\$ Commented Mar 16, 2017 at 5:32

1 Answer 1

5
\$\begingroup\$

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'
answered Mar 16, 2017 at 5:52
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.