A clean way to get the "true" base of a Path object?
Expected Inputs and Outputs:
a -> a
a.txt -> a
archive.tar.gz -> archive
directory/file -> file
d.x.y.z/f.a.b.c -> f
logs/date.log.txt -> date # Mine!
Here's my implementation that seems messy to me:
>>> from pathlib import Path
>>> example_path = Path("August 08 2015, 01'37'30.log.txt")
>>> example_path.stem
"August 08 2015, 01'37'30.log"
>>> example_path.suffixes
['.log', '.txt']
>>> suffixes_length = sum(map(len, example_path.suffixes))
>>> true_stem = example_path.name[:-suffixes_length]
>>> true_stem
"August 08 2015, 01'37'30"
Since it breaks Path
without suffixes:
>>> ns_path = Path("no_suffix")
>>> sl = sum(map(len, ns_path.suffixes))
>>> ns_path.name[:-sl]
''
So I need to check if the Path
suffix has:
>>> def get_true_stem(path: Path):
... if path.suffix:
... sl = sum(map(len, path.suffixes))
... return path.name[:-sl]
... else:
... return path.stem
...
>>>
>>> get_true_stem(example_path)
"August 08, 2015, 01'37'30"
>>> get_true_stem(ns_path)
"no_suffix"
And this is my current use case:
>>> file_date = datetime.strptime(true_stem, "%B %d %Y, %H'%M'%S")
>>> file_date
datetime.datetime(2015, 8, 8, 1, 37, 30)
>>> new_dest = format(file_date, "%Y-%m-%dT%H:%M:%S%z") + ".log" # ISO-8601
>>> shutil.move(str(example_path), new_dest)
Thank.
source to share
You can just do .split
it:
>>> Path('logs/date.log.txt').stem.split('.')[0]
'date'
os.path
works just as well:
>>> os.path.basename('logs/date.log.txt').split('.')[0]
'date'
It passes all tests:
In [11]: all(Path(k).stem.split('.')[0] == v for k, v in {
....: 'a': 'a',
....: 'a.txt': 'a',
....: 'archive.tar.gz': 'archive',
....: 'directory/file': 'file',
....: 'd.x.y.z/f.a.b.c': 'f',
....: 'logs/date.log.txt': 'date'
....: }.items())
Out[11]: True
source to share
How about a while while method where you keep taking .stem
until the path contains no suffixes, Example -
from pathlib import Path
example_path = Path("August 08 2015, 01'37'30.log.txt")
example_path_stem = example_path.stem
while example_path.suffixes:
example_path_stem = example_path.stem
example_path = Path(example_path_stem)
Note that the while loop breaks out of the loop when it example_path.suffixes
returns an empty list (since an empty list is False as in a boolean context).
Example / Demo -
>>> from pathlib import Path
>>> example_path = Path("August 08 2015, 01'37'30.log.txt")
>>> example_path_stem = example_path.stem
>>> while example_path.suffixes:
... example_path_stem = example_path.stem
... example_path = Path(example_path_stem)
...
>>> example_path_stem
"August 08 2015, 01'37'30"
For your second input - no_suffix
-
>>> example_path = Path("no_suffix")
>>> example_path_stem = example_path.stem
>>> while example_path.suffixes:
... example_path_stem = example_path.stem
... example_path = Path(example_path_stem)
...
>>> example_path_stem
'no_suffix'
source to share