I'm reading learn python the hard way,
and on chapter 15 I'm suppose to use import
argv to assign variables and raw input to gain
user input. The script is:
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 = raw_input ("> ")
txt_again = open (file_again)
print txt_again.read ()
After running this script I get the error, too many values to unpack.
File "ex15.py", line 3, in
script , filename = argv
Value error: too many values to unpack
Best Answer
Just a couple of pointers...
Here you're importing argv to access command line parameters, and then expecting it to contain 2 arguments - script (arg 0) and filename to print (arg1). Although the trailing comma isn't syntatically incorrect, it's not required and just looks a bit odd. I nomally leave
argv
insidesys
instead of pulling it into the current namespace, but that's a matter of taste - it doesn't make a real difference. I would probably throw in a bit of error handling as well:All that
txt = (name)
is doing here is making txt have the value of filename. I believe you want to be makingtxt
a file object, so that you can.read()
from it:You've got the
open()
here, buttxt.again.read()
should betxt_again.read()
else you'll get anAttributeError
- so just change that and it's fine.Alternatively, file objects supporting seeking, so you could just
rewind
the file (as you've read the file to the end, there's nothing left to read anymore), by using: