Publish date: 2023-12-10
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?
9 Answers
An elegant way using pathlib.Path:
from pathlib import Path p = Path('mysequence.fasta') p.rename(p.with_suffix('.aln')) 4os.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) 5import 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
2Starting 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" I love pathlib :)
4Use 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" 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') 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') 1Sadly, I experienced a case of multiple dots on file name that splittext does not worked well... my work around:
file = r'C:\Docs\file.2020.1.1.xls' ext = '.'+ os.path.realpath(file).split('.')[-1:][0] filefinal = file.replace(ext,'') filefinal = file + '.zip' os.rename(file ,filefinal) >> file = r'C:\Docs\file.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'
ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoaXJoYGWAdnvCoZinn5mjtG6yyKWcZp2oqbKvv8iopWahnmK9usDHqKU%3D