I'm trying to make a python script that converts one file type to another, and I'd like to have the option to specify an output file, but a default to just change the extension on the default file name.
Eg: I want convert('foo.gb')
to output foo.faa
, but convert('foo.gb', 'bar.faa')
to output bar.faa
The way I've implemented this is:
#!/usr/bin/env python
def convert(inputFile, outputFile = None):
[code that converts data]
if not outputFile:
import re
name = re.match('(.+)\.\w+', inputFile)
outputFile = './{0}.faa'.format(name.group(1))
with open(outputFile, 'w+') as outFaa:
outputFaa.write([stuff to write])
So, it checks to see if an output has been specified, and if it hasn't, uses regular expressions to change the input file name to have the right extension. This code works, but seems somewhat sloppy, or at the very least not very readable. It would also break if the file name has a .
anywhere other than before the extension, which it might sometimes have.
Is there a better way to do this?