如何在Python中从文件名替换(或剥离)扩展名? [英] How to replace (or strip) an extension from a filename in Python?

查看:55
本文介绍了如何在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)

推荐答案

尝试

Try os.path.splitext it should do what you want.

import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'

这篇关于如何在Python中从文件名替换(或剥离)扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆