这是练习15从Learn Python的难题,但我使用Python 3。Python 3 - 从文件中读取文本
from sys import argv
script, filename = argv
txt = open(filename)
print ("Here's your file %r:") % filename
print txt.read()
print ("I'll also ask you to type it again:")
file_again = input()
txt_again = open(file_again)
print txt_again.read()
文件被保存为ex15.py,当我从终端运行它它读取ex15.txt正确第一次,但是当我请求它第二次,我得到一个错误
[email protected]:~/Desktop/python$ python ex15.py ex15.txt<br>
Here's your file 'ex15.txt':<br>
This is stuff I typed into a file.<br>
It is really cool stuff.<br>
Lots and lots of fun to have in here.<br>
I'll also ask you to type it again:<br>
ex15.txt <b>#now I type this in again, and I get a following error</b><br>
Traceback (most recent call last):<br>
File "ex15.py", line 11, in <<module>module><br>
file_again = input()<br>
File "<<string\>string>", line 1, in <<module>module><br>
NameError: name 'ex15' is not defined
怎么了?
你确定你在py3k上? –
for python 3你需要使用'print()'函数而不是'print'语句和[str.format()](http://docs.python.org/library/stdtypes.html#str.format)而不是'%'=>你没有使用python 3,检查你的操作系统的'.py'文件的默认解释器 – Aprillion
在print()上达成一致,但是你仍然可以在CPython 3.x中的字符串上使用%运算符。对于双版本代码,使用%可能是件好事。另外,pylint会针对类型问题进行检查。 – user1277476