diff options
Diffstat (limited to 'oslo_utils/fileutils.py')
-rw-r--r-- | oslo_utils/fileutils.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/oslo_utils/fileutils.py b/oslo_utils/fileutils.py index 909ed4b..36c0049 100644 --- a/oslo_utils/fileutils.py +++ b/oslo_utils/fileutils.py @@ -22,10 +22,12 @@ File utilities. import contextlib import errno import hashlib +import json import os import stat import tempfile import time +import yaml from oslo_utils import excutils @@ -158,3 +160,50 @@ def last_bytes(path, num): raise unread_bytes = fp.tell() return (fp.read(), unread_bytes) + + +def is_json(file_path): + """Check if file is of json type or not. + + This function try to load the input file using json.loads() + and return False if ValueError otherwise True. + + :param file_path: The file path to check + + :returns: bool + + """ + with open(file_path, 'r') as fh: + data = fh.read() + try: + json.loads(data) + return True + except ValueError: + return False + + +def is_yaml(file_path): + """Check if file is of yaml type or not. + + This function try to load the input file using yaml.safe_load() + and return True if loadable. Because every json file can be loadable + in yaml, so this function return False if file is loadable using + json.loads() means it is json file. + + :param file_path: The file path to check + + :returns: bool + + """ + with open(file_path, 'r') as fh: + data = fh.read() + is_yaml = False + try: + json.loads(data) + except ValueError: + try: + yaml.safe_load(data) + is_yaml = True + except yaml.scanner.ScannerError: + pass + return is_yaml |