「CSV」ファイルをPythonで読み込み, 「LIST」として格納する方法についての記事となっております。
データ構造
### Data Structure
### - SAMPLE
### - sample.csv
### - sample.py
実行ファイルの内容
one,two,three
four,five,six
seven,eight,nine
import csv
def option_001(filePath):
file_IO = open(filePath)
info_STR = file_IO.read()
row_LIST = info_STR.split("\n")
### print(row_LIST )
### ['one,two,three', 'four,five,six', 'seven,eight,nine']
data_LIST = [row_STR.split(",") for row_STR in row_LIST]
### print(data_LIST)
### [['one', 'two', 'three'], ['four', 'five', 'six'], ['seven', 'eight', 'nine']]
file_IO.close()
return data_LIST
def option_002(filePath):
with open(filePath) as file_IO:
info_STR = file_IO.read()
row_LIST = info_STR.split("\n")
### print(row_LIST )
### ['one,two,three', 'four,five,six', 'seven,eight,nine']
data_LIST = [row_STR.split(",") for row_STR in row_LIST]
### print(data_LIST)
### [['one', 'two', 'three'], ['four', 'five', 'six'], ['seven', 'eight', 'nine']]
return data_LIST
def option_003(filePath):
with open(filePath) as file_IO:
info_CSV = csv.reader(file_IO)
data_LIST = [val for val in info_CSV]
### print(data_LIST)
### [['one', 'two', 'three'], ['four', 'five', 'six'], ['seven', 'eight', 'nine']]
return data_LIST
### INPUT: File Path (str)
### OUTPUT: File Information (list)
FILE_PATH = "SAMPLE/sample.csv"
print(option_001(FILE_PATH))
### print(option_002(FILE_PATH))
### print(option_003(FILE_PATH))