预期输入和输出:
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!
这是我觉得很脏的实现:
>>> 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"
因为它在Path
没有后缀的 s 上中断:
>>> ns_path = Path("no_suffix")
>>> sl = sum(map(len, ns_path.suffixes))
>>> ns_path.name[:-sl]
''
所以我需要先检查是否Path
有后缀:
>>> 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"
这是我当前的用例:
>>> 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)
谢谢。