プログラミング入門II
2025.06.25
ファイル処理
全体としては import 文が使いこなせる人が半分,そうでない人が半分という感じでした.そして,パスワードロックがかかっているフォルダにあるファイルを別のフォルダに移動するとか,別のフォルダに保存するというようなことをしなかったために,ファイルを添付できなかった人がそこそこいたのが残念です.
かつてやったことのある宿題の処理がそのまま使えるので,全体としては出来ている人が多かったのですが,今回は残念ながらエラーになるものが3つも出てきてしまいました.しっかり動作確認してから提出しましょう. 実行時エラー: 24_18 24_26 24_28 解答用紙不使用: 23_68 以下は例によって問題あるプログラムの例です.参考にしてください.
with open(file_path, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
data = list(reader)
temperatures = []
dates = []
for month_idx, row in enumerate(data[:12]):
for day_idx, value in enumerate(row):
try:
temp = float(value)
temperatures.append(temp)
dates.append((month_idx + 1, day_idx + 1))
except ValueError:
continue
max_temp = max(temperatures)
min_temp = min(temperatures)
max_index = temperatures.index(max_temp)
min_index = temperatures.index(min_temp)
max_month, max_day = dates[max_index]
min_month, min_day = dates[min_index]
max_month_name = month_names[max_month]
min_month_name = month_names[min_month]
print(f"The highest temperature: {max_month_name} {max_day}, {max_temp} degree Celsius")
print(f"The lowest temperature: {min_month_name} {min_day}, {min_temp} degree Celsius")
解答例を見てもらえば分かるように,宿題のときと違うのは気温データを読み込むところだけなので,そこだけ書き換えればいいのに,上のようにどうにもよく分からない処理を書いている人がそこそこいました.実行結果も下のようにデタラメです.
The highest temperature: November 15, 32.7 degree Celsius The lowest temperature: February 17, -2.7 degree Celsius |
file_path = 'temp_data.csv' max_temp = float('-inf') min_temp = float('inf') max_date = '' min_date = '' with open(file_path, encoding='utf-8') as f: reader = csv.reader(f) next(reader) for row in reader: if len(row) < 2: continue date = row[0] try: temp = float(row[1]) except ValueError: continue if temp > max_temp: max_temp = temp max_date = date if temp < min_temp: min_temp = temp min_date = date print('\n------------------------\n') print(f"The highest temperature: {max_date}, {max_temp} degree Celsius") print(f"The lowest temperature: {min_date}, {min_temp} degree Celsius") print('\n------------------------\n') |
上のものもおなじように分からない処理を書いて,結果としておかしなものを表示することになっています.おまけに,ハイフンの行を変なところにコピペしているのでしょうかね?
------------------------ The highest temperature: 34.1, 34.2 degree Celsius The lowest temperature: 1.9, 0.2 degree Celsius ------------------------ |
ファイル処理について,CSV形式で保存されているテキストデータの読み込みや,計算結果のCSVへの書き出しを学習しました.卒業研究などでの測定データの処理などに発展する内容ですので,今回の内容も含めてしっかり基本を押さえておきましょう.
引き続きファイルの入出力について CSV 形式のファイルの取り扱いを通して学習します.
今回の演習問題です.
いつものようにMoodleを利用します.授業当日の18:00から閲覧可能で,締切りは30日月曜日の15:00です.
次回からは教科書には載っていない Matplotlib を使用したグラフの描画について学習します.出来る限り授業の前にライブラリのインストールを済ませておいてください.また numpy も使用しますので,そちらもお願いします.インストールは pip を使用して簡単にできます.
参考ページ