繁体   English   中英

Python 3 - 从文件中读取文本

[英]Python 3 - reading text from a file

这是来自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

怎么了?

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

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

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

     file_again = input() 

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

#!/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

你的打印声明暗示你没有像你在标题中所说的那样使用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'

您似乎没有使用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.XX它会说python 3.XX

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

尝试使用此代码,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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM