5

这是 Learn Python the Hard Way 中的练习 15,但我使用的是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,但是当我第二次请求它时,出现错误

user@user:~/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

怎么了?

4

4 回答 4

7

你肯定没有使用 Python 3。有几件事很明显:

  • 这些print语句没有括号(在 Python 3 中是必需的,但不是 2):

    print ("Here's your file %r:") % filename
    print txt.read()
    
    print txt_again.read()
    
  • eval这是在input()Python 3 中更改的调用:

    file_again = input()
    

Python 2 很可能是您系统上的默认设置,但您可以通过将其添加为脚本的第一行(如果您直接运行它,如./myscript.py),使您的脚本始终使用 Python 3:

#!/usr/bin/env python3

或者使用 Python 3 显式运行它:

python3 myscript.py

还有一点需要注意的是:当你完成文件时,你应该真正关闭它。您可以明确地执行此操作:

txt = open(filename)
# do stuff needing text
txt.close()

或者使用with语句并在块结束时处理它:

with open(filename) as txt:
    # do stuff needing txt
# txt is closed here
于 2012-10-18T22:27:30.970 回答
5

您的打印声明表明您没有像标题中所说的那样使用 py3k。

print txt.read()这在 py3k 中不起作用,因此请确保您实际使用的是 py3k。

你需要使用raw_input()而不是input()因为你在py 2.x.

示例 py 2.x:

>>> x=raw_input()
foo
>>> x=input()   # doesn't works as it tries to find the variable bar
bar                    
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'bar' is not defined

py 3.x 示例:

>>> x=input()
foo
>>> x       # works fine
'foo'
于 2012-10-18T22:21:27.920 回答
3

您似乎没有使用 python 3.0.. 来检查这一点,只需在终端窗口中输入:

python

并查看交互器启动时出现的信息行。

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel
32
Type "help", "copyright", "credits" or "license" for more information.

它应该是这样的,
forpython 2.7.3和 forpython 3.X.X它会说python 3.X.X

如果您使用的是 python 2.X,Ashwini Chaudhary则有正确答案。

于 2012-10-18T22:25:26.127 回答
0

试试这个代码,对于 py3k:

txt = open(filename, 'r')
print('Here\'s your file %r: ' % filename)
print(txt.read())
txt.close()

print('I\'ll also ask you to type it again: ')
file_again = input()
txt_again = open(file_again, 'r')
print(txt_again.read())
txt_again.close()
于 2012-10-19T19:02:27.723 回答