太多的价值无法解包 [英] Too many values to unpack

查看:96
本文介绍了太多的价值无法解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力学习python, 在第15章中,我想使用import argv分配变量和原始输入以获得 用户输入.脚本是:

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.

文件"ex15.py",第3行,在 脚本,文件名= argv
值错误:无法解包的值太多

File "ex15.py", line 3, in script , filename = argv
Value error: too many values to unpack

推荐答案

只是几个指针...

from sys import argv  

script, filename, = argv 

在这里,您要导入argv以访问命令行参数,然后期望它包含2个参数-脚本(arg 0)和要打印的文件名(arg1).尽管结尾的逗号在语法上不是不正确的,但这不是必需的,并且看起来有点奇怪.我通常将argv留在sys内,而不是将其拉入当前名称空间中,但这只是一个趣味问题-并没有真正的区别.我可能还会抛出一些错误处理:

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

txt = (name)在这里所做的所有事情都是使txt具有filename的值.我相信您想将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 ()

您在这里有open(),但是txt.again.read()应该是txt_again.read(),否则您会得到AttributeError-因此只需更改它就可以了.

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.

或者,文件对象支持查找,因此您可以使用以下方法来rewind文件(由于您已经读完文件,因此不再需要读取内容了).

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

这篇关于太多的价值无法解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆