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

1 python syntax-error

我在运行下面的代码时遇到了麻烦,(这是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()
Run Code Online (Sandbox Code Playgroud)

我尝试从终端运行它并获得以下内容:

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
Run Code Online (Sandbox Code Playgroud)

这是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."
Run Code Online (Sandbox Code Playgroud)

我正在撞墙!(Python 2.6.1,OS X 10.6.8)

DSM*_*DSM 6

python ex15_sample.txt 
Run Code Online (Sandbox Code Playgroud)

你为什么要告诉Python运行文本文件?你的意思不是更像

python ex15_sample.py ex15_sample.txt
Run Code Online (Sandbox Code Playgroud)

或者你称之为Python程序的任何东西?

  • 我们都去过那里。:^) (2认同)