開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のV部(モジュール)のまとめ演習2.(fromステートメント)を解いてみる。
その他参考書籍
2.(fromステートメント)
コード(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))
入出力結果(Terminal)
$ 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. >>> name='sample.py' >>> from sample import test1 >>> test1(name) 行数: 29 文字数: 647 >>> from sample import * >>> test1(name) 行数: 29 文字数: 647 >>> test2(name) 29 647 >>> quit() $
0 コメント:
コメントを投稿