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

前端 未结 11 967
独厮守ぢ
独厮守ぢ 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 13:58

    1) simple split('.')[-1] won't work correctly for the path as C:\foo.bar\Makefile so you need to extract basename first with os.path.basename(), and even in this case it will fail to split file without extension correctly. os.path.splitext do this under the hood.

    2) Despite the fact os.path.splitext is cross-platform solution it's not ideal. Let's looking at the special files with leading dot, e.g. .cvsignore, .bzrignore, .hgignore (they are very popular in some VCS as special files). os.path.splitext will return entire file name as extension, although it does not seems right for me. Because in this case name without extension is empty string. Although this is intended behavior of Python standard library, it's may be not what user wants actually.

提交回复
热议问题