Python 3 - 从文件中读取文本

时间:2012-10-18 22:17:25

标签: python python-3.x

这是来自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 个答案:

答案 0 :(得分:7)

你绝对不会使用Python 3.有一些事情可以说明这一点:

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

    print ("Here's your file %r:") % filename
    print txt.read()
    
    print txt_again.read()
    
  • 这是致电eval on input() changed in 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 statement并在块结束时处理它:

with open(filename) as txt:
    # do stuff needing txt
# txt is closed here

答案 1 :(得分: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'

答案 2 :(得分:3)

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

python

并查看interperator启动时出现的信息行。

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.

这应该是这样的,
对于python 2.7.3,对于python 3.X.X,它会改为python 3.X.X

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

答案 3 :(得分: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()