在Python中更改文件扩展名

137 投票
9 回答
203356 浏览
提问于 2025-04-15 23:06

假设我在 index.py 这个文件里使用CGI,我上传了一个文件 foo.fasta,想在显示的文件中把 foo.fasta 的文件后缀改成 foo.aln。我该怎么做呢?

9 个回答

86
import os
thisFile = "mysequence.fasta"
base = os.path.splitext(thisFile)[0]
os.rename(thisFile, base + ".aln")

这里的 thisFile 是你要修改的文件的绝对路径。

139

这里有一种优雅的方法,使用的是 pathlib.Path 这个库:

from pathlib import Path
p = Path('mysequence.fasta')
p.rename(p.with_suffix('.aln'))
108

os.path.splitext() 是一个用来分离文件名和扩展名的工具,比如把“文件.txt”分成“文件”和“.txt”。

os.rename() 是用来重命名文件或文件夹的,比如把“旧名字.txt”改成“新名字.txt”。

举个例子:

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

撰写回答