這是練習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