此章节练习涉及到写两个文件。一个正常的 ex15.py 文件,另外一个是 ex15_sample.txt,第二个文件并不是脚本,而是供你的脚本读取的文本文件。以下是后者的内容:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
书中 ex15.py代码:
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
代码修改为:
from sys import argv
script, filename = argv
txt = open(filename)
print("Here's your file %r:" % filename)
print(txt.read())
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())
输出结果:
执行python