Changing file extension in Python

Question:

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?

Asked By: MysticCodes

||

Answers:

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)
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

Answered By: FryDay

Use this:

os.path.splitext("name.fasta")[0]+".aln"

And here is how the above works:

The splitext method separates the name from the extension creating a tuple:

os.path.splitext("name.fasta")

the created tuple now contains the strings “name” and “fasta”.
Then you need to access only the string “name” which is the first element of the tuple:

os.path.splitext("name.fasta")[0]

And then you want to add a new extension to that name:

os.path.splitext("name.fasta")[0]+".aln"
Answered By: multigoodverse

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 🙂

Answered By: AnaPana

An elegant way using pathlib.Path:

from pathlib import Path
p = Path('mysequence.fasta')
p.rename(p.with_suffix('.aln'))
Answered By: Nikita Malyavin

Using pathlib and preserving full path:

from pathlib import Path
p = Path('/User/my/path')
new_p = Path(p.parent.as_posix() + '/' + p.stem + '.aln')
Answered By: PollPenn

As AnaPana mentioned pathlib is more new and easier in python 3.4 and there is new with_suffix method that can handle this problem easily:

from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')
Answered By: Mahdi Saravi

Sadly, I experienced a case of multiple dots on file name that splittext does not worked well… my work around:

file = r'C:Docsfile.2020.1.1.xls'
ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
filefinal = file.replace(ext,'')
filefinal = file + '.zip'
os.rename(file ,filefinal)
Answered By: Hugo Vares
>> file = r'C:Docsfile.2020.1.1.xls'
>> ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
>> filefinal = file.replace(ext,'.zip')
>> os.rename(file ,filefinal) 

Bad logic for repeating extension, sample: ‘C:Docs.xls_aaa.xls.xls’

Answered By: uDev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.