[Python-Dev] splitext('.cshrc')
Larry Hastings
larry at hastings.org
Tue Mar 6 22:43:19 CET 2007
Martin v. Löwis wrote:
> Ok - now I'm confused: do you consider this behavior
> (splitext('.pythonrc') == ('', '.pythonrc')) correct
> or not?
>
+1 on the behavior. However, the patch is special-casing a leading dot;
it would still fail on splitext(".."). If we're gonna fix the bug, I'd
rather we fixed it dead.
What follows is a cross-platform splitext(). It passes all the tests I
threw at it, also attached. If there is interest, I would be happy to
submit it as an alternate patch. If runtime speed is paramount, I could
lose the portability, and instead port my patch into all three *path.py
files natively (dropping os.sep and os.altsep).
Hope this helps,
/larry/
----------
import os
def splitext(f):
sepIndex = f.rfind(os.sep)
if os.altsep:
altsepIndex = f.rfind(os.altsep)
sepIndex = max(sepIndex, altsepIndex)
dotIndex = f.rfind(".")
if dotIndex > sepIndex:
# skip all leading dots
filenameIndex = sepIndex + 1
while filenameIndex < dotIndex:
if f[filenameIndex] != '.':
return f[:dotIndex], f[dotIndex:]
filenameIndex += 1
return f, ''
def splitextTest(path, filename, ext):
assert splitext(path) == (filename, ext)
assert splitext(os.sep + path) == (os.sep + filename, ext)
assert splitext("abc" + os.sep + path) == ("abc" + os.sep + filename, ext)
assert splitext("abc.def" + os.sep + path) == ("abc.def" + os.sep +
filename, ext)
if os.altsep:
assert splitext(os.altsep + path) == (os.altsep + filename, ext)
assert splitext("abc" + os.altsep + path) == ("abc" + os.altsep +
filename, ext)
assert splitext("abc.def" + os.altsep + path) == ("abc.def" +
os.altsep + filename, ext)
splitextTest("foo.bar", "foo", ".bar")
splitextTest("foo.boo.bar", "foo.boo", ".bar")
splitextTest("foo.boo.biff.bar", "foo.boo.biff", ".bar")
splitextTest(".csh.rc", ".csh", ".rc")
splitextTest("nodots", "nodots", "")
splitextTest(".cshrc", ".cshrc", "")
splitextTest("...manydots", "...manydots", "")
splitextTest("...manydots.ext", "...manydots", ".ext")
splitextTest(".", ".", "")
splitextTest("..", "..", "")
splitextTest("........", "........", "")
//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20070306/4848d482/attachment-0001.html
More information about the Python-Dev
mailing list