2013年3月21日木曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のV部(モジュール)のまとめ演習3.(__name__属性)を解いてみる。

その他参考書籍

3.(__name__属性)

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

def countLines1(name):
    with open(name) as f:
        return len(f.readlines())

def countChars1(name):
    with open(name) as f:
        return len(f.read())

def test1(name):
    for x, y in [("行数",countLines1(name)), ("文字数", countChars1(name))]:
        print("{0}: {1}".format(x, y))

# 結果的にopen関数を2回呼び出す事になるのをseek関数を使ってファイルの先頭に移動して
# open関数の呼び出しを1回だけにするように修正

def countLines2(file):
    return len(file.readlines())

def countChars2(file):
    return len(file.read())

def test2(name):
    with open(name) as f:
        print(countLines2(f))
        f.seek(0)
        print(countChars2(f))

if __name__ == '__main__':
    test2('sample.py')

入出力結果(Terminal)

$ ./sample.py
32
697
$ python
Python 3.3.0 (default, Sep 29 2012, 08:16:08) 
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sample
>>> sample.test2('sample.py')
32
697
>>> quit()
$

0 コメント:

コメントを投稿