refactor => create fileclasses

This commit is contained in:
stubbfel
2014-05-18 23:18:01 +02:00
parent 48353cab1c
commit 4ae29f9304
5 changed files with 123 additions and 24 deletions

View File

@@ -1,17 +1,30 @@
__author__ = 'stubbfel'
import json
import utilities.textfileutility as tfu
def write_json(filename, json_object):
valid_types = (dict, str)
if not isinstance(json_object, valid_types):
raise ValueError
if isinstance(json_object, str):
json_object = json.loads(json_object)
json_string = json.dumps(json_object, indent=4)
tfu.write_text_file(filename, json_string)
from utilities.textfileutility import TextFile
class JsonFile(TextFile):
def __init__(self, filename):
"""
init class
:param filename: path to the file
"""
super(JsonFile, self).__init__(filename)
def write_json(self, json_object):
"""
write a json object to a text file
:param json_object: json object, which has to be saved. If the object is a string,
the method will be check if its a valid json object
:raise ValueError: will be raised if json_object is not a dictionary or string or the json object is not valid
"""
valid_types = (dict, str)
assert isinstance(json_object, valid_types)
if isinstance(json_object, str):
json_object = json.loads(json_object)
json_string = json.dumps(json_object, indent=4)
self.write_text_file(json_string)

View File

@@ -1,11 +1,48 @@
__author__ = 'stubbfel'
import os.path
def write_text_file(filename, file_content):
class TextFile:
if not isinstance(filename, str):
raise ValueError
def __init__(self, filename):
"""
init the class and set the filename
:param filename:
"""
assert isinstance(filename, str)
self._filename = filename
with open(filename, 'w', newline='\n') as file:
file.write(file_content)
file.close()
def write_text_file(self, file_content):
"""
write strings to a text file
:param file_content: strings which has to been write i a text file
:raise ValueError: will be raised, when the content is not a string
"""
assert isinstance(self._filename, str)
with open(self._filename, 'w', newline='\n') as file:
file.write(file_content)
file.close()
def check_and_remove_file(self):
"""
Method remove this file, if the file don't exists the method don't call remove
"""
if self.exists_file:
os.remove(self._filename)
@property
def exists_file(self):
"""
check if this file exists or not
:return: true if the file exists, otherwise false
"""
return os.path.isfile(self._filename)
@property
def get_filename(self):
"""
get the file Name
:return: str
"""
assert isinstance(self._filename, str)
return self._filename