Python.use(better) #body: step02 -- open(file,"r")

記事一覧 Python.use(better)《Python3.1》

open(file,"r")

《著》森こねこ、小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28

課題を作成する過程を通して「ファイル操作」の理解を深めます。
※ Python1.5 で作成した例題を、Python3.1 で再構成しました。

事例:モジュールを起動する

■ 全項目を確認する

全ステップの「項目」を確認するには、関数 do を利用します。

$ python -i my_range.py
>>> do()
...
2: step02 -- open(file,"r")
■ 各項目を実行する

各ステップの「動作」を確認するには、関数 do に実引数を指定します。

>>> do(2)
>>> # -------------------------------------------------- step02
>>> body('temp')
A - 65
B - 66
C - 67
>>>

新たにファイル 'temp' を作成するとともに、各行を出力します。

事例:コードの解説

    def body(file):
        with open(file,"w") as s:
            for e in "ABC":
                s.write("%s - %d\n"%(e,ord(e)))

        with open(file,"r") as s:
            for e in s:
                print(e,end="")
《余録》テストケース
def ex_body0(local, n):
    X = 'body({0!r})'.format(n)
    print_(X, local)
■ #1: with/as 文
        with open(file,"w") as s:
            for e in "ABC":
                s.write("%s - %d\n"%(e,ord(e)))

with に続く式 open(file,"w") を評価すると、

  • そのリターン値が変数 s に設定されるとともに、
  • with ブロックに記述したコードが実行されます。

with ブロックで例外を生成しないなら、

  • 自動的にメソッド close が呼び出されます。

with 文に伴うコンテキストマネージャーが、ファイル s に対してメソッド close を呼び出します。

■ #2: 組み込み関数 open
        with open(file,"r") as s:
            for e in s:
                print(e,end="")

with に続く式 open(file,"r") を評価すると、

  • 指定した名前 file のファイル s(ストリーム)を生成した後で、
  • ファイル s の各行 e を出力 print します。

》こちらに移動中です《
TOP


関連記事

Last updated♪2009/12/14