
如有翻译问题欢迎评论指出,谢谢。
Python 如何从路径中获取没有拓展名的文件名?
-
Joan Venge asked:
- Python 中如何获取不包括拓展名的文件名?
- 例如这个路径
/path/to/some/file.txt
里的file
。
-
Answers:
-
Geo – vote: 1561
-
得到不包括拓展名的文件名:
-
import os print(os.path.splitext("/path/to/some/file.txt")[0])
-
输出:
-
/path/to/some/file
-
特别注意:如果文件名有多个点,只有最后一个代表拓展的点会被去除。
例如: -
import os print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])
-
输出:
-
/path/to/some/file.txt.zip
-
如果需要处理这种情况,可以看其他人的回答。
注:这篇翻译的三个回答没有涉及到这个情况。 -
mxdbld – vote: 792
-
from pathlib import Path Path('/root/dir/sub/file.ext').stem
-
将返回
-
'file'
-
注意,如果文件有多个拓展名,
.stem
只会移除最后一个。例如,Path('file.tar.gz').stem
将会返回'file.tar'
。 -
gimel – vote: 705
-
这样坐:
-
>>> import os >>> base=os.path.basename('/root/dir/sub/file.ext') >>> base 'file.ext' >>> os.path.splitext(base) ('file', '.ext') >>> os.path.splitext(base)[0] 'file'
-
特别注意:如果文件名中有超过一个
.
,只有最后一个会被移除。例如: -
/root/dir/sub/file.ext.zip -> file.ext /root/dir/sub/file.ext.tar.gz -> file.ext.tar
-
见其它回答来解决这个问题。
注:这篇翻译的三个回答没有涉及到这个情况。
-
How to get the filename without the extension from a path in Python?
-
Joan Venge asked:
- How to get the filename without the extension from a path in Python?
Python 中如何获取不包括拓展名的文件名? - For instance, if I had
/path/to/some/file.txt
, I would wantfile
.
例如这个路径/path/to/some/file.txt
里的file
。
- How to get the filename without the extension from a path in Python?
-
Answers:
-
Geo – vote: 1561
-
Getting the name of the file without the extension:
得到不包括拓展名的文件名: -
import os print(os.path.splitext("/path/to/some/file.txt")[0])
-
Prints:
输出: -
/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])
-
Prints:
输出: -
/path/to/some/file.txt.zip
-
See other answers below if you need to handle that case.
如果需要处理这种情况,可以看其他人的回答。
注:这篇翻译的三个回答没有涉及到这个情况。 -
mxdbld – vote: 792
-
Use
.stem
frompathlib
in Python 3.4+
在 Python 3.4+ 中可以使用pathlib
中的.stem
。 -
from pathlib import Path Path('/root/dir/sub/file.ext').stem
-
will return
将返回 -
'file'
-
Note that if your file has multiple extensions
.stem
will only remove the last extension. For example,Path('file.tar.gz').stem
will return'file.tar'
.
注意,如果文件有多个拓展名,.stem
只会移除最后一个。例如,Path('file.tar.gz').stem
将会返回'file.tar'
。 -
gimel – vote: 705
-
You can make your own with:
这样坐: -
>>> import os >>> base=os.path.basename('/root/dir/sub/file.ext') >>> base 'file.ext' >>> os.path.splitext(base) ('file', '.ext') >>> os.path.splitext(base)[0] 'file'
-
Important note: If there is more than one
.
in the filename, only the last one is removed. For example:
特别注意:如果文件名中有超过一个.
,只有最后一个会被移除。例如: -
/root/dir/sub/file.ext.zip -> file.ext /root/dir/sub/file.ext.tar.gz -> file.ext.tar
-
See below for other answers that address that.
见其它回答来解决这个问题。
注:这篇翻译的三个回答没有涉及到这个情况。
-
近期评论