Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing file extension in Python

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?

like image 465
MysticCodes Avatar asked May 24 '10 20:05

MysticCodes


People also ask

How do you change a file extension in Python?

When changing the extension, you're basically just renaming the file and changing the extension. In order to do that, you need to split the filename by '. ' and replace the last entry by the new extension you want.

How do you change a filename in Python?

Use rename() method of an OS module rename() method to rename a file in a folder. Pass both the old name and a new name to the os. rename(old_name, new_name) function to rename a file.


1 Answers

An elegant way using pathlib.Path:

from pathlib import Path p = Path('mysequence.fasta') p.rename(p.with_suffix('.aln')) 
like image 154
Nikita Malyavin Avatar answered Oct 12 '22 23:10

Nikita Malyavin