如何从 Python 中的文件名替换(或去除)扩展名? [英] How can I replace (or strip) an extension from a filename in Python?
问题描述
Python 中是否有内置函数可以替换(或删除,无论如何)文件名的扩展名(如果有的话)?
Is there a built-in function in Python that would replace (or remove, whatever) the extension of a filename (if it has one)?
示例:
print replace_extension('/home/user/somefile.txt', '.jpg')
在我的例子中:/home/user/somefile.txt
会变成 /home/user/somefile.jpg
In my example: /home/user/somefile.txt
would become /home/user/somefile.jpg
我不知道这是否重要,但我需要在我正在编写的 SCons 模块中使用它.(所以也许我可以使用一些 SCons 特定功能?)
I don't know if it matters, but I need this for a SCons module I'm writing. (So perhaps there is some SCons specific function I can use ?)
我想要一些干净的.对字符串中所有出现的 .txt
进行简单的字符串替换显然是不干净的.(如果我的文件名是 somefile.txt.txt.txt
,这将失败)
I'd like something clean. Doing a simple string replacement of all occurrences of .txt
within the string is obviously not clean. (This would fail if my filename is somefile.txt.txt.txt
)
推荐答案
尝试 os.path.splitext 它应该做你想做的事.
Try os.path.splitext it should do what you want.
import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'
这篇关于如何从 Python 中的文件名替换(或去除)扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!