如何从Python中的路径获取没有扩展名的文件名?
问题描述:
如何从 Python 中的路径获取不带扩展名的文件名?
How to get the filename without the extension from a path in Python?
例如,如果我有 /path/to/some/file.txt"
,我会想要 file"
.
For instance, if I had "/path/to/some/file.txt"
, I would want "file"
.
答
获取不带扩展名的文件名:
Getting the name of the file without the extension:
import os
print(os.path.splitext("/path/to/some/file.txt")[0])
打印:
/path/to/some/file
重要说明:如果文件名有多个点,则仅删除最后一个后的扩展名.例如:
Important Note: If the filename has multiple dots, only the extension after the last one is removed. For example:
import os
print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])
打印:
/path/to/some/file.txt.zip
如果您需要处理这种情况,请参阅下面的其他答案.
See other answers below if you need to handle that case.