我在input_file上做了很多处理步骤。为了避免在每一步都考虑到output_filename,我创建了以下名称生成函数:
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对我来说很大。你能检查我的代码并帮助我改进它吗?
发布于 2017-03-16 05:52:24
您可以通过使用os.path.splitext()来显着地简化函数:
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'https://codereview.stackexchange.com/questions/157889
复制相似问题