Skip to content

zerohertzLib.util.csv

Functions:

Name Description
read_csv

CSV (Comma-Separated Values) 혹은 TSV (Tab-Separated Values)를 작성하는 function

write_csv

CSV (Comma-Separated Values) 혹은 TSV (Tab-Separated Values)를 작성하는 function

read_csv

read_csv(path: str, header: bool = True) -> dict[int | str, list[str]]

CSV (Comma-Separated Values) 혹은 TSV (Tab-Separated Values)를 작성하는 function

Parameters:

Name Type Description Default
path str

입력될 CSV 혹은 TSV 경로 및 file 이름

required
header bool

Header의 존재 유무

True

Returns:

Type Description
dict[int | str, list[str]]

Header의 값을 기반으로 column에 따라 list 로 구성

Note

Header가 존재하지 않는 경우 0 부터 차례대로 key 값 정의

Examples:

>>> zz.util.read_csv("star_craft.csv")
defaultdict(<class 'list'>, {'id': ['5hi9', 'gor2', 'gk03'], 'Races': ['Protoss', 'Terran', 'Zerg'], 'Scores': ['1248', '2309', '291']})
>>> zz.util.read_csv("star_craft.tsv")
defaultdict(<class 'list'>, {'id': ['5hi9', 'gor2', 'gk03'], 'Races': ['Protoss', 'Terran', 'Zerg'], 'Scores': ['1248', '2309', '291']})
>>> zz.util.read_csv("star_craft.csv", header=False)
defaultdict(<class 'list'>, {0: ['id', '5hi9', 'gor2', 'gk03'], 1: ['Races', 'Protoss', 'Terran', 'Zerg'], 2: ['Scores', '1248', '2309', '291']})
>>> zz.util.read_csv("star_craft.tsv", header=False)
defaultdict(<class 'list'>, {0: ['id', '5hi9', 'gor2', 'gk03'], 1: ['Races', 'Protoss', 'Terran', 'Zerg'], 2: ['Scores', '1248', '2309', '291']})
Source code in zerohertzLib/util/csv.py
def read_csv(path: str, header: bool = True) -> dict[int | str, list[str]]:
    """CSV (Comma-Separated Values) 혹은 TSV (Tab-Separated Values)를 작성하는 function

    Args:
        path: 입력될 CSV 혹은 TSV 경로 및 file 이름
        header: Header의 존재 유무

    Returns:
        Header의 값을 기반으로 column에 따라 `list` 로 구성

    Note:
        Header가 존재하지 않는 경우 `0` 부터 차례대로 key 값 정의

    Examples:
        >>> zz.util.read_csv("star_craft.csv")
        defaultdict(<class 'list'>, {'id': ['5hi9', 'gor2', 'gk03'], 'Races': ['Protoss', 'Terran', 'Zerg'], 'Scores': ['1248', '2309', '291']})
        >>> zz.util.read_csv("star_craft.tsv")
        defaultdict(<class 'list'>, {'id': ['5hi9', 'gor2', 'gk03'], 'Races': ['Protoss', 'Terran', 'Zerg'], 'Scores': ['1248', '2309', '291']})
        >>> zz.util.read_csv("star_craft.csv", header=False)
        defaultdict(<class 'list'>, {0: ['id', '5hi9', 'gor2', 'gk03'], 1: ['Races', 'Protoss', 'Terran', 'Zerg'], 2: ['Scores', '1248', '2309', '291']})
        >>> zz.util.read_csv("star_craft.tsv", header=False)
        defaultdict(<class 'list'>, {0: ['id', '5hi9', 'gor2', 'gk03'], 1: ['Races', 'Protoss', 'Terran', 'Zerg'], 2: ['Scores', '1248', '2309', '291']})
    """
    data = defaultdict(list)
    keys = []
    with open(path, "r", encoding="utf-8") as file:
        raws = file.readlines()
    if path.endswith(".csv"):
        delimiter = ","
    elif path.endswith(".tsv"):
        delimiter = "\t"
    else:
        raise ValueError("File is not CSV or TSV")
    if header:
        raw = raws[0]
        for key in raw.strip().split(delimiter):
            keys.append(key)
        raws = raws[1:]
    else:
        for key in range(len(raws[0].strip().split(delimiter))):
            keys.append(key)
    for raw in raws:
        for key, value in zip(keys, raw.strip().split(delimiter)):
            data[key].append(value)
    return data

write_csv

write_csv(data: list[list[Any]], path: str, tsv: bool = False) -> str

CSV (Comma-Separated Values) 혹은 TSV (Tab-Separated Values)를 작성하는 function

Parameters:

Name Type Description Default
data list[list[Any]]

입력 data (header 포함 무관)

required
path str

출력될 CSV 혹은 TSV 경로 및 file 이름

required
tsv bool

TSV 작성 여부

False

Returns:

Type Description
str

File의 절대 경로

Examples:

>>> zz.util.write_csv([["id", "Races", "Scores"], ["5hi9", "Protoss", 1248], ["gor2", "Terran", 2309], ["gk03", "Zerg", 291]], "zerohertzLib/star_craft")
'/.../star_craft.csv'
>>> zz.util.write_csv([["id", "Races", "Scores"], ["5hi9", "Protoss", 1248], ["gor2", "Terran", 2309], ["gk03", "Zerg", 291]], "zerohertzLib/star_craft", True)
'/.../star_craft.tsv'
Source code in zerohertzLib/util/csv.py
def write_csv(data: list[list[Any]], path: str, tsv: bool = False) -> str:
    """CSV (Comma-Separated Values) 혹은 TSV (Tab-Separated Values)를 작성하는 function

    Args:
        data: 입력 data (header 포함 무관)
        path: 출력될 CSV 혹은 TSV 경로 및 file 이름
        tsv: TSV 작성 여부

    Returns:
        File의 절대 경로

    Examples:
        >>> zz.util.write_csv([["id", "Races", "Scores"], ["5hi9", "Protoss", 1248], ["gor2", "Terran", 2309], ["gk03", "Zerg", 291]], "zerohertzLib/star_craft")
        '/.../star_craft.csv'
        >>> zz.util.write_csv([["id", "Races", "Scores"], ["5hi9", "Protoss", 1248], ["gor2", "Terran", 2309], ["gk03", "Zerg", 291]], "zerohertzLib/star_craft", True)
        '/.../star_craft.tsv'
    """
    if tsv:
        with open(f"{path}.tsv", "w", encoding="utf-8") as file:
            for data_ in data:
                file.writelines("\t".join(list(map(str, data_))) + "\n")
        return os.path.abspath(f"{path}.tsv")
    with open(f"{path}.csv", "w", encoding="utf-8") as file:
        for data_ in data:
            file.writelines(",".join(list(map(str, data_))) + "\n")
    return os.path.abspath(f"{path}.csv")