add default objects if loading fails

This commit is contained in:
2019-06-12 15:40:23 +02:00
parent 4ec84c49ac
commit 458a8a7659

View File

@@ -2,6 +2,8 @@
# -*- coding: utf-8 -*-
"""Read and write data to or from file.
:Date: 2019-06-12
.. module:: data
:platform: *nix, Windows
:synopsis: Handle data files.
@@ -11,7 +13,7 @@
from __future__ import print_function
import pickle
def data_read(file_name, x_column, y_column):
def data_read(file_name, x_column, y_column, default=None, verbose=False):
"""Read ascii data file.
:param filename: file to read
@@ -20,27 +22,43 @@ def data_read(file_name, x_column, y_column):
:type x_column: int
:param y_column: column index for the y data (first column is 0)
:type y_column: int
:param default: return object if data loading fails
:type default: object
:param verbose: verbose information (default = False)
:type verbose: bool
:returns: x and y
:rtype: tuple(list, list)
"""
import re
file = open(file_name)
x = []
y = []
for row in file:
fields = re.split(r'\s+', row.strip())
#print(filds)
x.append(float(fields[x_column]))
y.append(float(fields[y_column]))
file.close()
x = default
y = default
if verbose:
print('check if data is available')
try:
file = open(file_name)
x = []
y = []
for row in file:
fields = re.split(r'\s+', row.strip())
#print(filds)
x.append(float(fields[x_column]))
y.append(float(fields[y_column]))
file.close()
except IOError:
if verbose:
print('data file not found')
return x, y
def data_load(file_name, verbose=False):
def data_load(file_name, default=None, verbose=False):
"""Load stored program objects from binary file.
:param file_name: file to load
:type file_name: str
:param default: return object if data loading fails
:type default: object
:param verbose: verbose information (default = False)
:type verbose: bool
@@ -56,7 +74,7 @@ def data_load(file_name, verbose=False):
print('found:')
print(object_data)
except IOError:
object_data = None
object_data = default
if verbose:
print('no saved datas found')
return object_data