【Python入門】Pythonを用いたCSVファイルを読み込む方法とは?PythonでのCSVファイルの読み込み方法を徹底解説

Python

CSV(Comma-Separated Values)ファイルは、データをテキスト形式で表現するための一般的なフォーマットです。データは行と列の形で表現され、各セルはカンマで区切られます。CSVファイルは、ExcelやGoogleスプレッドシートなどの一般的なプログラムで簡単に作成、編集、閲覧できます。本記事では、PythonによるCSVファイルを読み込む方法を紹介します。

下記の様な内容で悩んでいる/困っている場合に使える方法を参考までにご共有させて頂きます。

・Pythonの場合、どうやってCSVファイルを使うの?
・Pythonのリスト(配列)は、どの様にCSVファイルを扱うのだろうか?

CSVファイルの読み込み(自作関数)

関数の定義

def readFileCSVWithHeader(input_path:str, input_encoding:str="utf_8", bool_header:bool=True, bool_eval:bool=True) -> tuple:
    if not existData(input_path): print(f"[ERROR] Does Not Exist >> {input_path}"); return None 
    with open(input_path, mode='r', encoding=input_encoding) as f: lines = list(csv.reader(f))
    
    if bool_eval:
        new_lines = []
        for line in lines:
            new_line = []
            for value in line:
                try: value = eval(value)
                except: pass 
                new_line.append(value)
            new_lines.append(new_line)
        lines = new_lines

    header = {}
    if bool_header: 
        for column_id, label in enumerate(lines[0]): header[label] = column_id
        lines.pop(0)
    
    return (header, lines)

使用例

データの内容(sample.csv)

head_1,head_2,head_3
apple,APPLE,りんご
123,1.23,1e23
True,False,None

プログラムの内容

input_file_path = "INPUT/sample.csv"
csv_header, csv_data = readFileCSVWithHeader(input_file_path, "shift_jis")

print(f"Header:\n{csv_header} {type(csv_header)}\n")
print(f"Data:\n{csv_data} {type(csv_data)}\n")
Header:
{'head_1': 0, 'head_2': 1, 'head_3': 2} <class 'dict'>

Data:
[['apple', 'APPLE', 'りんご'], [123, 1.23, 1e+23], [True, False, None]] <class 'list'>

Pythonで取り扱うCSVデータの内容

まとめ

Pythonはデータ活用する上で、とても便利なプログラミング言語です。この記事で紹介させて頂いた方法で「CSVファイル」に格納されている情報を読み込み、データ処理/データ分析/データ管理等でぜひ活用してみてください。

関連検索ワード

How to read a CSV file with Python?

関連キーワード

python, 入門, 初心者, ファイル, 読み込み, CSV, file, read