Python splitext 函数

12 投票
1 回答
4847 浏览
提问于 2025-04-17 02:26

在Python中,为什么os.path.splitext使用'.'作为文件扩展名的分隔符,而不是os.extsep呢?

1 个回答

5

os.extsep 是通过导入 os.path.extsep 来定义的。不过你说得对,os.path.splitext() 一直使用 .,无论 os.path.extsep 是什么:

来自 os.py(版本 3.2.2):

from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
    devnull)

来自 ntpath.py(它变成了 os.path):

extsep = '.'
[...]
def _get_dot(path):
    if isinstance(path, bytes):
        return b'.'
    else:
        return '.'   # instead of return extsep! [Comment by me, not in source]
[...]
def splitext(p):
    return genericpath._splitext(p, _get_sep(p), _get_altsep(p),
                                 _get_dot(p))

还有,来自 genericpath.py

def _get_dot(path):
    if isinstance(path, bytes):
        return b'.'
    else:
        return '.'

所以 os.path() 确实定义了扩展名分隔符两次。

现在这可能没什么大不了的,因为它不会很快改变(反正所有支持的平台都是一样的)。但从某种意义上说,这违反了 DRY 原则。

撰写回答