Skip to main content
 首页 » 编程设计

python之读取文本文件时出现语法错误

2025年05月04日18lvdongjie

<分区>

我在运行以下代码时遇到问题(这是 Zed Shaw 的“艰难地学习 Python”中的练习 15):

from sys import argv 
 
script, filename = argv 
 
txt = open(filename) 
 
print "Here's your file %r." % filename print txt.read() 
 
print "Type the filename again: " file_again = raw_input("==>") 
 
txt_again = open(file_again) 
 
print txt_again.read() 
 
txt.close() txt_again.close() 

我尝试从终端运行它并获得以下信息:

dominics-macbook-4:MyPython Dom$ python ex15_sample.txt 
  File "ex15_sample.txt", line 1 
    This is stuff I typed into a file. 
                  ^ 
SyntaxError: invalid syntax 

这是 ex15_sample.txt 的内容:

"This is stuff I typed into a file. 
It is really cool stuff. 
Lots and lots of fun to have in here." 

我要用头撞墙了! (Python 2.6.1, OS X 10.6.8)