forked from dtcooper/python-fitparse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
67 lines (52 loc) · 1.71 KB
/
utils.py
File metadata and controls
67 lines (52 loc) · 1.71 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import io
import re
from collections.abc import Iterable
from pathlib import PurePath
class FitParseError(ValueError):
pass
class FitEOFError(FitParseError):
pass
class FitCRCError(FitParseError):
pass
class FitHeaderError(FitParseError):
pass
METHOD_NAME_SCRUBBER = re.compile(r'\W|^(?=\d)')
UNIT_NAME_TO_FUNC_REPLACEMENTS = (
('/', ' per '),
('%', 'percent'),
('*', ' times '),
)
def scrub_method_name(method_name, convert_units=False):
if convert_units:
for replace_from, replace_to in UNIT_NAME_TO_FUNC_REPLACEMENTS:
method_name = method_name.replace(
replace_from, '%s' % replace_to,
)
return METHOD_NAME_SCRUBBER.sub('_', method_name)
def fileish_open(fileish, mode):
"""
Convert file-ish object to BytesIO like object.
:param fileish: the file-ihs object (str, BytesIO, bytes, file contents)
:param str mode: mode for the open function.
:rtype: BytesIO
"""
if mode is not None and any(m in mode for m in ['+', 'w', 'a', 'x']):
attr = 'write'
else:
attr = 'read'
if hasattr(fileish, attr) and hasattr(fileish, 'seek'):
# BytesIO-like object
return fileish
elif isinstance(fileish, str):
# file path
return open(fileish, mode)
# pathlib obj
if isinstance(fileish, PurePath):
return fileish.open(mode)
# file contents
return io.BytesIO(fileish)
def is_iterable(obj):
"""Check, if the obj is iterable but not string or bytes.
:rtype bool"""
# Speed: do not use iter() although it's more robust, see also https://stackoverflow.com/questions/1952464/
return isinstance(obj, Iterable) and not isinstance(obj, (str, bytes))