Python – Too many values to unpack

argvpython

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

from sys import argv  

script, filename, = argv 

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 inside sys 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:

import sys

try:
    script, filename = sys.argv
except ValueError as e:
    raise SystemExit('must supply single filename as argument')

txt = (filename) 

print " Here's your file %r :" % filename 
print  txt.read() 

All that txt = (name) is doing here is making txt have the value of filename. I believe you want to be making txt a file object, so that you can .read() from it:

txt = open(filename)
print "Here's the file contents of:", 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 ()

You've got the open() here, but txt.again.read() should be txt_again.read() else you'll get an AttributeError - 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:

txt.seek(0)
print txt.read()