Skip to content
Snippets Groups Projects
Commit defbbf46 authored by Jirka's avatar Jirka
Browse files

file handlers

parent 77494dd8
No related branches found
No related tags found
2 merge requests!5City knowledge base nomad,!3City knowledge base nomad
import csv
from typing import List
class CsvHandler:
@staticmethod
def __removeInitSpace__(word: str) -> str:
"""
Removes space at index 0 if present
"""
if word.startswith(" "):
return word[1:]
else:
return word
@staticmethod
def load(filepath: str) -> (List[str], List[dict]):
"""
Loads csv file
:param filepath: path to csv file
:return: tuple of (list of header params, list of dict in format: {header1: value1, header2: value2,...})
"""
item_list = []
with open(filepath, 'r') as csvFile:
header = csvFile.readline().split(",")
for i in range(1, len(header)):
header[i] = CsvHandler.__removeInitSpace__(header[i])
reader = csv.reader(csvFile)
for row in reader:
for i in range(1, len(row)):
row[i] = CsvHandler.__removeInitSpace__(row[i])
dic = {}
for i in range(1, len(header)):
dic[header[i]] = row[i]
item_list.append(dic)
csvFile.close()
return header, item_list
@staticmethod
def save(filepath: str, header: list, csv_as_list_dic: List[dict]) -> None:
"""
Saves csv file into disk
:param filepath: path to save csv file (with filename)
:param header: header to save into file
:param csv_as_list_dic: list of dic in format {header1: value1, header2: value2,...}
:return: None
"""
with open(filepath, 'w') as csvFile:
header_line = ""
for headerItem in header:
header_line += headerItem + ","
header_line = header_line[0:len(header_line) - 1]
csvFile.write(header_line + "\n")
for row in csv_as_list_dic:
line = ""
for headerItem in header:
line = line + row[headerItem] + ","
line = line[0:len(line) - 1]
csvFile.write(line + "\n")
csvFile.close()
import json
class JsonHandler:
@staticmethod
def load(filepath: str) -> dict:
"""
Loads json from disk
:param filepath: path to json file (with filename)
:return: json as dict
"""
with open(filepath, 'r') as jsonFile:
json_as_string = jsonFile.read()
jsonFile.close()
return json.loads(json_as_string)
@staticmethod
def save(filepath: str, json_as_dict: dict) -> None:
"""
Saves json into disk
:param filepath: path to save json file (with filename)
:param json_as_dict: dict
:return: None
"""
json_as_string = json.dumps(json_as_dict, indent=4)
with open(filepath, 'w') as jsonFile:
jsonFile.write(json_as_string)
jsonFile.close()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment