Pythonのファイル操作・例外処理・モジュールを学びます。実用的なプログラムに欠かせない3つの機能です。
ファイルの読み書き
# ファイルに書き込む
with open("sample.txt", "w", encoding="utf-8") as f:
f.write("Hello, Python!\n")
f.write("2行目のテキスト\n")
# ファイルを読む
with open("sample.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 1行ずつ読む
with open("sample.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())with文を使うとファイルを自動で閉じてくれるため、常にwith open()の形で書くのが推奨です。
例外処理(try/except)
try:
num = int(input("数字を入力: "))
result = 100 / num
print(f"結果: {result}")
except ValueError:
print("数字を入力してください")
except ZeroDivisionError:
print("0で割ることはできません")
except Exception as e:
print(f"予期しないエラー: {e}")
finally:
print("処理終了")モジュールのインポート
import os
import sys
import datetime
from pathlib import Path
print(os.getcwd()) # カレントディレクトリ
print(datetime.date.today()) # 今日の日付
print(Path.home()) # ホームディレクトリ
print(sys.version) # Pythonのバージョンまとめ
- ファイル操作はwith open()を使うとファイルが自動クローズされる
- try/except/finallyで例外を安全に処理できる
- importで標準ライブラリや外部モジュールを使える



コメント