2014年2月25日火曜日

開発環境

Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART II.(Types and Operations)、Test Your Knowledge: Part II Exercises、11.(Files)を解いてみる。

その他参考書籍

11.(Files)

コード(BBEdit)

sample.py

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

with open('myfile.txt', 'w') as f:
    f.write('Hello file world!')

sample1.py

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

with open('myfile.txt') as f:
    print(f.read())

sample2.py

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

try:
    with open('../myfile.txt') as f:
        print(f.read())
except Exception as err:
    print(type(err), err, err.args)

入出力結果(Terminal)

$ ls myfile.txt
ls: myfile.txt: No such file or directory
$ ./sample.py
$ ls myfile.txt 
myfile.txt
$ ./sample1.py
Hello file world!
$ ./sample2.py
<class 'IOError'> [Errno 2] No such file or directory: '../myfile.txt' (2, 'No such file or directory')
$

0 コメント:

コメントを投稿