Changing file extension in Python
Solution 1:
An elegant way using pathlib.Path:
from pathlib import Path
p = Path('mysequence.fasta')
p.rename(p.with_suffix('.aln'))
Solution 2:
os.path.splitext()
, os.rename()
for example:
# renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension
pre, ext = os.path.splitext(renamee)
os.rename(renamee, pre + new_extension)
Solution 3:
import os
thisFile = "mysequence.fasta"
base = os.path.splitext(thisFile)[0]
os.rename(thisFile, base + ".aln")
Where thisFile = the absolute path of the file you are changing
Solution 4:
Starting from Python 3.4 there's pathlib built-in library. So the code could be something like:
from pathlib import Path
filename = "mysequence.fasta"
new_filename = Path(filename).stem + ".aln"
https://docs.python.org/3.4/library/pathlib.html#pathlib.PurePath.stem
I love pathlib :)