1

I'm learning Python using Learn Python The Hard Way. It is very good and efficient but at one point I had a crash. I've searched the web but could not find an answer. Here is my question:

One of the exercises tell to do this:

from sys import argv

script, filename = argv

and then it proceeds to doing things that I do understand:

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')

What does the first part mean?

P.S. the error I get is:

syntaxError Unexpected character after line continuation character

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191

3 Answers3

2
script, filename = argv

This is unpacking the sequence argv. The first element goes into script, and the second element goes into filename. In general, this can be done with any iterable, as long as there exactly as many variables on the left-hand-side as are items in the iterable on the right-hand-side.

The code you show seems ok, I don't know why you are getting a syntax-error there.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Exactly, the only problem was that the user was wrong (me). I interpreted what you said there as write in the script. Totally wrong ofcours. I had to write it on the commandline. Thanks tough for your help. – Robin Dorstijn Nov 20 '11 at 21:20
1

Unexpected character after line continuation character means that you have split a command in two lines using the continuation character \ (see this question) but added some characters (e.g. a white space) after it.

But I do not see any \ in your code...

Community
  • 1
  • 1
Don
  • 16,928
  • 12
  • 63
  • 101
1

The code works fine, put the code in the example in the codefile.py and pass a dummydata file to it:

$ 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.
$

This should solve your problem

avasal
  • 14,350
  • 4
  • 31
  • 47