如何从 Python 中的文件名替换(或去除)扩展名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3548673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:40:52  来源:igfitidea点击:

How to replace (or strip) an extension from a filename in Python?

pythonscons

提问by ereOn

Is there a built-in function in Python that would replace (or remove, whatever) the extension of a filename (if it has one) ?

Python 中是否有一个内置函数可以替换(或删除,无论如何)文件名的扩展名(如果有的话)?

Example:

例子:

print replace_extension('/home/user/somefile.txt', '.jpg')

In my example: /home/user/somefile.txtwould become /home/user/somefile.jpg

在我的例子中:/home/user/somefile.txt会变成/home/user/somefile.jpg

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

我不知道这是否重要,但是我正在编写的 SCons 模块需要它。(所以也许我可以使用一些 SCons 特定功能?)

I'd like something clean. Doing a simple string replacement of all occurrences of .txtwithin the string is obviously not clean. (This would fail if my filename is somefile.txt.txt.txt)

我想要干净的东西。对字符串中的所有出现进行简单的字符串替换.txt显然不干净。(如果我的文件名是 ,这将失败somefile.txt.txt.txt

采纳答案by jethro

Try os.path.splitextit should do what you want.

试试os.path.splitext它应该做你想做的。

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

回答by Katriel

As @jethro said, splitextis the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension must bethe part of the filename coming after the final period:

正如@jethro 所说,这splitext是一种巧妙的方法。但在这种情况下,自己拆分它很容易,因为扩展名必须是最后一个句点之后的文件名的一部分:

filename = '/home/user/somefile.txt'
print( filename.rsplit( ".", 1 )[ 0 ] )
# '/home/user/somefile'

The rsplittells Python to perform the string splits starting from the right of the string, and the 1says to perform at most one split (so that e.g. 'foo.bar.baz'-> [ 'foo.bar', 'baz' ]). Since rsplitwill always return a non-empty array, we may safely index 0into it to get the filename minus the extension.

rsplit告诉Python来执行从字符串的右侧开始字符串分割,并1说,最多只有一个分裂执行(从而使得例如'foo.bar.baz'- > [ 'foo.bar', 'baz' ])。由于rsplit将始终返回一个非空数组,我们可以安全地对其进行索引0以获取文件名减去扩展名。

回答by user2802945

Another way to do is to use the str.rpartition(sep)method.

另一种方法是使用str.rpartition(sep)方法。

For example:

例如:

filename = '/home/user/somefile.txt'
(prefix, sep, suffix) = filename.rpartition('.')

new_filename = prefix + '.jpg'

print new_filename

回答by IvanD

I prefer the following one-liner approach using str.rsplit():

我更喜欢使用str.rsplit()的以下单行方法:

my_filename.rsplit('.', 1)[0] + '.jpg'

Example:

例子:

>>> my_filename = '/home/user/somefile.txt'
>>> my_filename.rsplit('.', 1)
>>> ['/home/user/somefile', 'txt']

回答by AnaPana

For Python >= 3.4:

对于 Python >= 3.4:

from pathlib import Path

filename = '/home/user/somefile.txt'

p = Path(filename)
new_filename = p.parent.joinpath(p.stem + '.jpg') # PosixPath('/home/user/somefile.jpg')
new_filename_str = str(new_filename) # '/home/user/somefile.jpg'

回答by JS.

Expanding on AnaPana's answer, how to removean extension using pathlib(Python >= 3.4):

扩展 AnaPana 的答案,如何使用pathlib(Python >= 3.4)删除扩展名:

>>> from pathlib import Path

>>> filename = Path('/some/path/somefile.txt')

>>> filename_wo_ext = filename.with_suffix('')

>>> filename_replace_ext = filename.with_suffix('.jpg')

>>> print(filename)
/some/path/somefile.ext    

>>> print(filename_wo_ext)
/some/path/somefile

>>> print(filename_replace_ext)
/some/path/somefile.jpg

回答by Michael Hall

Handling multiple extensions

处理多个扩展

In the case where you have multiple extensions this one-liner using pathliband str.replaceworks a treat:

在您有多个扩展的情况下,此单行使用pathlibstr.replace有效:

Remove/strip extensions

删除/剥离扩展

>>> from pathlib import Path
>>> p = Path("/path/to/myfile.tar.gz")
>>> str(p).replace("".join(p.suffixes), "")
'/path/to/myfile'

Replace extensions

替换扩展

>>> p = Path("/path/to/myfile.tar.gz")
>>> new_ext = ".jpg"
>>> str(p).replace("".join(p.suffixes), new_ext)
'/path/to/myfile.jpg'

If you also want a pathlibobject output then you can obviously wrap the line in Path()

如果您还想要一个pathlib对象输出,那么您显然可以将行包起来Path()

>>> Path(str(p).replace("".join(p.suffixes), ""))
PosixPath('/path/to/myfile')