web-dev-qa-db-fra.com

Modification de l'extension de fichier dans Python

Supposons que de index.py Avec CGI, j'ai un fichier de publication foo.fasta Pour afficher le fichier. Je souhaite que l'extension de fichier de foo.fasta Soit foo.aln Dans le fichier d'affichage. Comment puis-je le faire?

51
MysticCodes

os.path.splitext() , os.rename()

par exemple:

# 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)
34
import os
thisFile = "mysequence.fasta"
base = os.path.splitext(thisFile)[0]
os.rename(thisFile, base + ".aln")

Où thisFile = le chemin absolu du fichier que vous modifiez

60
FryDay

Une manière élégante d'utiliser pathlib.Path :

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

À partir de Python 3.4 il y a pathlib bibliothèque intégrée. Le code pourrait donc être quelque chose comme:

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

J'adore pathlib :)

19
AnaPana

Utilisez ceci:

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

Et voici comment cela fonctionne:

La méthode splitext sépare le nom de l'extension créant un Tuple:

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

le Tuple créé contient désormais les chaînes "name" et "fasta". Ensuite, vous devez accéder uniquement à la chaîne "nom" qui est le premier élément du tuple:

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

Et puis vous voulez ajouter une nouvelle extension à ce nom:

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

Utilisation de pathlib et préservation du chemin complet:

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