44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
import csv
|
|
import json
|
|
from abc import ABCMeta, abstractmethod
|
|
|
|
from src.system_var.constants import (CSV_DELIMITER, CSV_LINE_TERMINATOR,
|
|
CSV_QUOTE_CHAR, FILE_CHAR_CODE,
|
|
FILE_MODE_WRITE)
|
|
|
|
|
|
class FileWriter(metaclass=ABCMeta):
|
|
|
|
def __init__(self, file_path: str, content) -> None:
|
|
self._file_path = file_path
|
|
self._content = content
|
|
|
|
@abstractmethod
|
|
def write(self) -> str:
|
|
"""ファイルを書き出し、ファイルパスを返す
|
|
|
|
Returns:
|
|
str: 書き出し先のファイルパス
|
|
"""
|
|
pass
|
|
|
|
|
|
class JsonWriter(FileWriter):
|
|
|
|
def write(self) -> str:
|
|
with open(self._file_path, mode=FILE_MODE_WRITE, encoding=FILE_CHAR_CODE, newline='') as f:
|
|
json.dump(self._content, f, ensure_ascii=False, )
|
|
|
|
return self._file_path
|
|
|
|
|
|
class CsvWriter(FileWriter):
|
|
|
|
def write(self) -> str:
|
|
with open(self._file_path, mode=FILE_MODE_WRITE, encoding=FILE_CHAR_CODE, newline='') as f:
|
|
writer = csv.writer(f, delimiter=CSV_DELIMITER, lineterminator=CSV_LINE_TERMINATOR,
|
|
quotechar=CSV_QUOTE_CHAR, doublequote=True, quoting=csv.QUOTE_ALL,
|
|
strict=True)
|
|
writer.writerows(self._content)
|
|
return self._file_path
|