Discussion:
Another pathlib suggestion
Antony Lee
2014-05-21 20:38:01 UTC
Permalink
Handling of Paths with multiple extensions is currently not so easy with
pathlib. Specifically, I don't think there is an easy way to go from
"foo.tar.gz" to "foo.ext", because Path.with_suffix only replaces the last
suffix.

I would therefore like to suggest either

1/ add Path.replace_suffix, such that
Path("foo.tar.gz").replace_suffix(".tar.gz", ".ext") == Path("foo.ext")
(this would also provide extension-checking capabilities, raising
ValueError if the first argument is not a valid suffix of the initial
path); or

2/ add a second argument to Path.with_suffix, "n_to_strip" (although
perhaps with a better name), defaulting to 1, such that
Path("foo.tar.gz").with_suffix(".ext", 0) == Path("foo.tar.gz.ext")
Path("foo.tar.gz").with_suffix(".ext", 1) == Path("foo.tar.ext")
Path("foo.tar.gz").with_suffix(".ext", 2) == Path("foo.ext") # set
n_to_strip to len(path.suffixes) for stripping all of them.
Path("foo.tar.gz").with_suffix(".ext", 3) raises a ValueError.

Best,
Antony
Antony Lee
2014-06-23 01:05:37 UTC
Permalink
After some more thought, a better API may be to provide a "with_suffixes"
method, such that "p.with_suffixes(*s).suffixes == s" (just like
"p.with_suffix(s) == s").
For example, we'd have
Path("foo.tar.gz").with_suffixes(".ext") == Path("foo.ext")
Path("foo.ext").with_suffixes(".tar", ".gz") == Path("foo.tar.gz")

I guess this is a less popular topic than discussing new empty set literals
though :) but if you really like Unicode, you could just use
https://github.com/ehamberg/vim-cute-python

Antony
Post by Antony Lee
Handling of Paths with multiple extensions is currently not so easy with
pathlib. Specifically, I don't think there is an easy way to go from
"foo.tar.gz" to "foo.ext", because Path.with_suffix only replaces the last
suffix.
I would therefore like to suggest either
1/ add Path.replace_suffix, such that
Path("foo.tar.gz").replace_suffix(".tar.gz", ".ext") == Path("foo.ext")
(this would also provide extension-checking capabilities, raising
ValueError if the first argument is not a valid suffix of the initial
path); or
2/ add a second argument to Path.with_suffix, "n_to_strip" (although
perhaps with a better name), defaulting to 1, such that
Path("foo.tar.gz").with_suffix(".ext", 0) == Path("foo.tar.gz.ext")
Path("foo.tar.gz").with_suffix(".ext", 1) == Path("foo.tar.ext")
Path("foo.tar.gz").with_suffix(".ext", 2) == Path("foo.ext") # set
n_to_strip to len(path.suffixes) for stripping all of them.
Path("foo.tar.gz").with_suffix(".ext", 3) raises a ValueError.
Best,
Antony
Loading...