From 55c00d743dedbf039d8e43a7e89a6a7749213776 Mon Sep 17 00:00:00 2001 From: Zerohertz Date: Fri, 17 Nov 2023 17:09:14 +0900 Subject: [PATCH] :sparkles: Feat: Write CSV, TSV, JSON (close: #69) --- test/test_util.py | 35 ++++++++++++++++++ zerohertzLib/util/__init__.py | 3 +- zerohertzLib/util/write.py | 69 +++++++++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 zerohertzLib/util/write.py diff --git a/test/test_util.py b/test/test_util.py index 28af6c6a..425f1a5f 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -26,3 +26,38 @@ def test_JsonDir(): assert jsd._getKey("language") == "head/repo/language" assert type(jsd.unique("sha")) == set jsd.tree() + + +def test_write_csv(): + zz.util.write_csv( + [ + ["id", "종족", "점수"], + ["5hi9", "프로토스", 1248], + ["gor2", "테란", 2309], + ["gk03", "저그", 291], + ], + "star_craft", + ) + assert "star_craft.csv" in os.listdir() + + +def test_write_csv(): + zz.util.write_tsv( + [ + ["id", "종족", "점수"], + ["5hi9", "프로토스", 1248], + ["gor2", "테란", 2309], + ["gk03", "저그", 291], + ], + "star_craft", + True, + ) + assert "star_craft.tsv" in os.listdir() + + +def test_write_json(): + zz.util.write_json( + [{"id": "4169", "전투력": 4209, "정보": ["아무", "거나"]}] * 100, + "star_craft", + ) + assert "star_craft.json" in os.listdir() diff --git a/zerohertzLib/util/__init__.py b/zerohertzLib/util/__init__.py index f8a85e42..a7b5ce01 100644 --- a/zerohertzLib/util/__init__.py +++ b/zerohertzLib/util/__init__.py @@ -1,4 +1,5 @@ from zerohertzLib.util.data import MakeData from zerohertzLib.util.json import Json, JsonDir +from zerohertzLib.util.write import write_csv, write_json -__all__ = ["Json", "JsonDir", "MakeData"] +__all__ = ["Json", "JsonDir", "MakeData", "write_csv", "write_json"] diff --git a/zerohertzLib/util/write.py b/zerohertzLib/util/write.py new file mode 100644 index 00000000..fa3812c0 --- /dev/null +++ b/zerohertzLib/util/write.py @@ -0,0 +1,69 @@ +import json +import os +from typing import Any, Dict, List, Optional, Union + + +def write_csv(data: List[List[Any]], path: str, tsv: Optional[bool] = False) -> str: + """CSV (Comma-Separated Values) 혹은 TSV (Tab-Separated Values)를 작성하는 함수 + + Args: + data (``List[List[Any]]``): 입력 데이터 (header 포함 무관) + path (``str``): 출력될 CSV 혹은 TSV 경로 및 파일명 + tsv (``Optional[bool]``): TSV 작성 여부 + + Returns: + ``str``: 파일의 절대 경로 + + Examples: + >>> zz.util.write_csv([["id", "종족", "점수"], ["5hi9", "프로토스", 1248], ["gor2", "테란", 2309], ["gk03", "저그", 291]], "zerohertzLib/star_craft") + '/.../star_craft.csv' + >>> zz.util.write_csv([["id", "종족", "점수"], ["5hi9", "프로토스", 1248], ["gor2", "테란", 2309], ["gk03", "저그", 291]], "zerohertzLib/star_craft", True) + '/.../star_craft.tsv' + """ + if tsv: + with open(f"{path}.tsv", "w", encoding="utf-8") as f: + for d in data: + f.writelines("\t".join(list(map(str, d))) + "\n") + return os.path.abspath(f"{path}.tsv") + else: + with open(f"{path}.csv", "w", encoding="utf-8") as f: + for d in data: + f.writelines(",".join(list(map(str, d))) + "\n") + return os.path.abspath(f"{path}.csv") + + +def write_json(data: Union[Dict[Any, Any], List[Dict[Any, Any]]], path: str) -> str: + """JSON (JavaScript Object Notation)를 작성하는 함수 + + Args: + data (``Dict[Any, Any]``): 입력 데이터 (header 포함 무관) + path (``str``): 출력될 json 파일의 경로 및 파일명 + + Returns: + ``str``: 파일의 절대 경로 + + Examples: + >>> zz.util.write_json([{"id": "4169", "전투력": 4209, "정보": ["아무", "거나"]}]*100, "zerohertzLib/star_craft") + '/.../star_craft.json' + [ + { + "id": "4169", + "전투력": 4209, + "정보": [ + "아무", + "거나" + ] + }, + { + "id": "4169", + "전투력": 4209, + "정보": [ + "아무", + "거나" + ] + }, + ... + """ + with open(f"{path}.json", "w", encoding="utf-8") as f: + json.dump(data, f, indent=4, ensure_ascii=False) + return os.path.abspath(f"{path}.json")