Benefits of os.path.splitext over regular .split?

前端 未结 11 982
独厮守ぢ
独厮守ぢ 2020-12-08 13:16

In this other question, the votes clearly show that the os.path.splitext function is preferred over the simple .split(\'.\')[-1] string manipulatio

11条回答
  •  余生分开走
    2020-12-08 14:00

    Well, there are separate implementations for separate operating systems. This means that if the logic to extract the extension of a file differs on Mac from that on Linux, this distinction will be handled by those things. I don't know of any such distinction so there might be none.


    Edit: @Brian comments that an example like /directory.ext/file would of course not work with a simple .split('.') call, and you would have to know both that directories can use extensions, as well as the fact that on some operating systems, forward slash is a valid directory separator.

    This just emphasizes the use a library routine unless you have a good reason not to part of my answer.

    Thanks @Brian.


    Additionally, where a file doesn't have an extension, you would have to build in logic to handle that case. And what if the thing you try to split is a directory name ending with a backslash? No filename nor an extension.

    The rule should be that unless you have a specific reason not to use a library function that does what you want, use it. This will avoid you having to maintain and bugfix code others have perfectly good solutions to.

提交回复
热议问题