Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os
from pathlib import Path
from datetime import datetime
def check_filepath(filepath: (str, Path),
makedir: bool = True,
overwrite: bool = False,
expand: str = 'date',
**kwargs) -> Path:
"""
Checks a filepath existence and possibly creates directories
:param filepath: filepath to the target
:param makedir: create nonexistent directories in the filepath
:param overwrite: toggles allowance to overwrite existing data in the filepath
:param expand: 'date' (default): expands existing files with datetime (up to minute),
'num': expands with running digit
:return filepath: The correct path to the existing or created folder
"""
filepath = Path(filepath)
if not filepath.parent.exists():
if makedir:
os.makedirs(Path(filepath.parent))
else:
raise ValueError('Filepath does not exist. To create, rerun with makedir = True.')
if not overwrite:
if expand == 'date':
if filepath.exists():
filepath = Path(filepath.as_posix().replace(filepath.stem + filepath.suffix,
filepath.stem + '__{date}'.format(
date=datetime.now().strftime("%Y-%m-%d_%H-%M"))
+ filepath.suffix))
elif expand == 'num':
i = (len(filepath.suffix) + 1) * -1
while filepath.exists():
if filepath.name[i].isdigit():
if int(filepath.name[i]) + 1 < 10:
filepath = Path(filepath.as_posix().replace(filepath.name[i],
str(int(filepath.name[i]) + 1)))
else:
i -= 1
else:
filepath = Path(filepath.as_posix().replace(filepath.stem + filepath.suffix,
filepath.stem + '__1' + filepath.suffix))
else:
raise ValueError('Can not expand with ' + expand + ', only date and num are valid.')
return filepath