開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python 3.4 (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART Ⅱ.(Types and Operations)、Test Your Knowledge: Part II Exercises 11.(Files)を解いてみる。
その他参考書籍
- Pythonチュートリアル 第2版
- Python クックブック 第2版 (原書(最新版))
- Programming Python
- Python Pocket Reference (Pocket Reference (O'Reilly))
11.(Files)
コード(BBEdit)
sample11_1.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sys
with open(sys.argv[1], 'w') as f:
print('Hello file world!', file=f)
sample11_2.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sys
with open(sys.argv[1]) as f:
print(f.read(), end='')
入出力結果(Terminal, IPython)
$ ./sample11_1.py myfile.txt
$ ./sample11_2.py myfile.txt
Hello file world!
$ ls myfile.txt
myfile.txt
$ rm myfile.txt
remove myfile.txt? y
$ ./sample11_1.py ../myfile.txt
$ ./sample11_2.py ../myfile.txt
Hello file world!
$ ls myfile.txt
ls: myfile.txt: No such file or directory
$ ls ../myfile.txt
../myfile.txt
$ rm ../myfile.txt
remove ../myfile.txt? y
$ ./sample11_1.py temp_dir/myfile.txt
Traceback (most recent call last):
File "./sample11_1.py", line 6, in <module>
with open(sys.argv[1], 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'temp_dir/myfile.txt'
$ mkdir temp_dir
$ ./sample11_1.py temp_dir/myfile.txt
$ ./sample11_2.py temp_dir/myfile.txt
Hello file world!
$ ls myfile.txt
ls: myfile.txt: No such file or directory
$ ls temp_dir/*
temp_dir/myfile.txt
$
0 コメント:
コメントを投稿