Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python splitext

In python, why is os.path.splitext using '.' as extension separator instead of os.extsep?

like image 990
bla Avatar asked Sep 16 '11 13:09

bla


People also ask

What is Splitext Python?

splitext() method in Python is used to split the path name into a pair root and ext. Here, ext stands for extension and has the extension portion of the specified path while root is everything except ext part.

Is path A Splitext?

splitext() is a built-in Python function that splits the pathname into the pair of root and ext. The ext stands for extension and has the extension portion of the specified path, while the root is everything except the ext part. Everything before the final slash and everything after it.

How do you break a path in Python?

split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that.

What is __ file __ Python?

The __file__ variable: __file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.


1 Answers

os.extsep is defined by importing os.path.extsep. But you're right, os.path.splitext() always uses ., regardless of os.path.extsep:

From os.py (3.2.2):

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

From ntpath.py (which becomes 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))

Also, from genericpath.py:

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

So os.path() does in fact define the extension separator twice.

Now it probably doesn't matter because it's not going to change anytime soon (it's the same on all supported platforms anyway). But in a way, it violates the DRY principle.

like image 108
Tim Pietzcker Avatar answered Sep 28 '22 05:09

Tim Pietzcker