译(四十一)-Python从路径中获取文件名
如有翻译问题欢迎评论指出,谢谢。
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/fileImportant 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.zipSee other answers below if you need to handle that case.
如果需要处理这种情况,可以看其他人的回答。
注:这篇翻译的三个回答没有涉及到这个情况。mxdbld - vote: 792
Use
.stemfrompathlibin Python 3.4+
在 Python 3.4+ 中可以使用pathlib中的.stem。from pathlib import Path Path('/root/dir/sub/file.ext').stemwill return
将返回'file'Note that if your file has multiple extensions
.stemwill only remove the last extension. For example,Path('file.tar.gz').stemwill 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.tarSee below for other answers that address that.
见其它回答来解决这个问题。
注:这篇翻译的三个回答没有涉及到这个情况。


共有 0 条评论