Warm tip: This article is reproduced from serverfault.com, please click

string-如何从Python路径中获取不带扩展名的文件名?

(string - How to get the filename without the extension from a path in Python?)

发布于 2009-03-24 16:41:03

如何从Python路径中获取不带扩展名的文件名?

例如,如果有的话"/path/to/some/file.txt",我会想要的"file"

Questioner
Joan Venge
Viewed
0
5,043 2020-05-04 06:13:01

获取不带扩展名的文件名:

import os
print(os.path.splitext("/path/to/some/file.txt")[0])

印刷:

/path/to/some/file

的文档os.path.splitext

重要说明:如果文件名包含多个点,则仅删除最后一个扩展名之后的扩展名。例如:

import os
print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])

印刷:

/path/to/some/file.txt.zip

如果你需要处理这种情况,请参见下面的其他答案。