1

我正在使用Learn Python The Hard Way 学习 Python。这是非常好的和高效的,但有一次我崩溃了。我在网上搜索过,但找不到答案。这是我的问题:

其中一项练习告诉你这样做:

from sys import argv

script, filename = argv

然后它继续做我理解的事情:

print "we are going to erase %r." % filename
print "if you don't want that, hit CTRL-C (^C)."
print "if you do want that, hit RETURN."

raw_input("?")

print "opening the file..." 
target = open(filename, 'w')

第一部分是什么意思?

PS我得到的错误是:

syntaxError 行继续字符后的意外字符

4

3 回答 3

2
script, filename = argv

这是解包序列 argv。第一个元素进入script,第二个元素进入filename。通常,只要左侧的变量与右侧的可迭代项中的项目数量完全相同,就可以使用任何可迭代对象来完成此操作。

您显示的代码似乎没问题,我不知道您为什么会出现语法错误。

于 2011-11-17T09:53:04.360 回答
1

Unexpected character after line continuation character意味着您已使用连续字符将命令分成两行\(请参阅此问题),但在其后添加了一些字符(例如空格)。

但是我\在您的代码中看不到任何内容...

于 2011-11-17T09:56:16.963 回答
1

代码工作正常,将代码放在 codefile.py 中的示例中,并将一个 dummydata 文件传递​​给它:

$ python codefile.py dummydatafile.txt 
 We're going to erase 'test1.txt'.
 If you don't want that, hit CTRL-C (^C).
 If you do want that, hit RETURN.
 ?
 Opening the file...
 Truncating the file. Goodbye!
 Now I'm going to ask you for three lines.
 line 1: 
 line 2: 
 line 3: 
 I'm going to write these to the file.
 And finally, we close it.
$

这应该可以解决您的问题

于 2011-11-17T10:12:37.123 回答