Python.use(better) #body: step07 -- def body(file, end=None):
‖記事一覧‖ Python.use(better)《Python3.1》
body: step07 -- def body(file, end=None):
《著》森こねこ、小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28
課題を作成する過程を通して「ファイル操作」の理解を深めます。
※ Python1.5 で作成した例題を、Python3.1 で再構成しました。
事例:コードの解説
def body(file, end=None): with open(file) as s: s = s.readlines() format = "%%%dd: %%s"%len("%d"%len(s)) s = s[:end] for i,e in enumerate(s): n = i+1 print(format%(n,e),end="") ## ---------------------------------------- local = locals() ex_body2(local, "temp")
《前例》をもとに、テストファイルを生成する部分を、関数 ex_body として抽出(リファクタリング)します。
■ #1: スライス
s = s[:end]
先頭から end の手前までの要素を列挙した、部分リスト s が得られます。
事例:モジュールを起動する
■ 全項目を確認する
全ステップの「項目」を確認するには、関数 do を利用します。
$ python -i my_range.py >>> do() 0: step00 -- open(file,"w") 1: step01 -- s.write(...) 2: step02 -- open(file,"r") 3: step03 -- for i,e in enumerate(f): 4: step04x -- f.readlines() 5: step05 -- print(format%(n,e),end="") 6: step06 -- def body(file): 7: step07 -- def body(file, end=None): 8: step08 -- def body(file, start=1, end=None): 9: step09 -- print("".join(s),end="") >>>
■ 各項目を実行する
各ステップの「動作」を確認するには、関数 do に実引数を指定します。
>>> do(7) >>> # -------------------------------------------------- step07 >>> body('temp') 1: A - 65 2: B - 66 3: C - 67 4: D - 68 5: E - 69 6: F - 70 7: G - 71 8: H - 72 9: I - 73 10: J - 74 >>> body('temp',end=3) 1: A - 65 2: B - 66 3: C - 67 >>>
新たにファイル 'temp' を作成するとともに、行番号に続いて各行を出力します。
- 先頭行から 3 行目までを出力します。
《余録》テストケース
def ex_body2(local, n):
ex_body1(local, n)
source = '''
body({0!r},end=3)
'''.split("\n")
for e in source[1:-1]:
print_(e.format(n), local)
》こちらに移動中です《
↑TOP