Fix Python – Changing file extension in Python

Question

Asked By – MysticCodes

Suppose from index.py with CGI, I have post file foo.fasta to display file. I want to change foo.fasta‘s file extension to be foo.aln in display file. How can I do it?

Now we will see solution for issue: Changing file extension in Python


Answer

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)

This question is answered By – Ignacio Vazquez-Abrams

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0