ymLogs

学びとゲームとITと。

【Python】CSVファイルをwith openするメモ

CSV(comma separated values)ファイルをpythonのwith openを利用して開きデータ処理を行う例のメモです。

詳しい説明は省きます。

aaa.csvの中身 (拡張子.txtでも可)

商品名,価格,個数

ペン,150,5

消しゴム,50,3

定規,120,2

 

.pyファイルの中身

b=[ ]  #商品一覧

c=[ ] #値段一覧

d=[ ] #個数一覧

 

with open(r"aaa.csv",encoding="UTF-8") as file: #相対パスで記述

    file.readline() #1行目のラベルを読み飛ばす

    for line in file: #CSVファイルの各行に対して繰り返す

        a=line.split(",") #コンマ区切りの部分を要素とするリストaができる

        b.append(a[0])

        c.append(int(a[1]))

        d.append(int(a[2]))

 

print(b) #商品一覧

print(c) #値段一覧

print(d) #個数一覧

 

S=0 #合計金額

for x in range(len(c)):

    S=S+c[x]*d[x]

print(S)

 

実行結果


['ペン', '消しゴム', '定規']
[150, 50, 120]
[5, 3, 2]
1140