简体   繁体   English

获取 Python 中不带扩展名的文件名

[英]Get Filename Without Extension in Python

If I have a filename like one of these:如果我有一个像以下之一的文件名:

1.1.1.1.1.jpg

1.1.jpg

1.jpg

How could I get only the filename, without the extension?我怎么能只得到文件名,没有扩展名? Would a regex be appropriate?正则表达式是否合适?

In most cases, you shouldn't use a regex for that. 在大多数情况下,您不应该使用正则表达式。

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name. 这也将通过保留整个名称来正确处理像.bashrc这样的文件名。

>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')

如果我必须使用正则表达式执行此操作,我会这样做:

s = re.sub(r'\.jpg$', '', s)

No need for regex. 不需要正则表达式。 os.path.splitext is your friend: os.path.splitext是你的朋友:

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')

You can use stem method to get file name. 您可以使用stem方法获取文件名。

Here is an example: 这是一个例子:

from pathlib import Path

p = Path(r"\\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file

One can also use the string slicing.也可以使用字符串切片。

>>> "1.1.1.1.1.jpg"[:-len(".jpg")]
'1.1.1.1.1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM