0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Python】csv.DictReaderで数値(int型のデータ)を読み込む

Posted at

はじめに

プログラミング初学者です.CSVファイルをPythonのcsv.DictReaderで読み込む際に起きたエラーとその解決法を共有します.

環境

  • Python 3.9.4
ターミナル
$ python3 --version
Python 3.9.4

エラー発生時のコード

  • 読み込み対象のファイル
food_calories.csv
food,calorie
ramen,443
coffee,7
cheesecake,281
hamburger,300
chickencurry,690
  • 先のCSVファイルを読み込むコード
add_calories.py
import csv

sum_of_calories = 0

with open("food_calories.csv") as file:
    data = csv.DictReader(file)
    for row in data:
        name = row["food"]
        calorie = row["calorie"]

        print("name : %s, calorie : %d" % (name, calorie))

        sum_of_calories += calorie

print("sum = %d" % sum_of_calories)  

発生したエラー

次のエラーが発生しました.

ターミナル
$ python3 add_calories.py
Traceback (most recent call last):
 File "/hogehoge/add_calories.py", line 11, in <module>
  print("name : %s, calorie : %d" % (name, calorie))
TypeError: %d format: a number is required, not str

解決方法

csv.DictReaderは読み込んだデータを文字列(str型)として扱うので,int型に変換する必要がありました.

calorie = int(row["calorie"])

実行結果

プログラムを動かすことができました.

ターミナル
$ python3 add_calories.py
name : ramen, calorie : 443
name : coffee, calorie : 7
name : cheesecake, calorie : 281
name : hamburger, calorie : 300
name : chickencurry, calorie : 690
sum = 1721

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?