Python ValueError : too many values to unpack, solution?

北战南征 提交于 2019-12-13 08:16:34

问题


Im getting this error and i have no idea what it means, i can get the program to print the files from there values but its just a long incoherent now im trying to get it to print it in an organized manor and thats where the issues arise.

import os 
def listfiles (path):
    files = []
    for dirName, subdirList, fileList in os.walk(path):
        dir = dirName.replace(path, '')
        for fname in fileList:
            files.append(os.path.join(dir, fname))
    return files

a = input('Enter a primary file path: ')
b = input('Enter a secondary file path: ')

x = listfiles(a)
y = llistfiles(b)

files_only_x = set(x) - set (y)
files_only_y = set(y) - set (x)

this next line of code is where python is saying the error is

for dirName, subdirList, fileList in files_only_x:
    print ('Directory: %s' % dirName)
    for fname in fileList:
        print ('\%s' % fname)

回答1:


Look at the data flow:

You call listfiles() with a path. It collects all files below that path in a list.

(BTW, IMHO dir = dirName.replace(path, '') is dangerous. What happens if path is lib/ and you encouter a sub path lib/misc/collected/lib/whatever? While this path males not much sense, it might have been created...)

You return this list from listfiles() and then convert them into sets.

If you try to iterate over these sets, you get one path per iteration step.




回答2:


Your files_only_x is a set of single values; your listfiles() function returns a list of strings, not of tuples with 3 values:

for fname in files_only_x:
    print ('\\%s' % fname)



回答3:


You built files as a list of strings, therefore the loop in your 2nd code block is wrong as it suggests files is list of 3-value tuples.



来源:https://stackoverflow.com/questions/19937261/python-valueerror-too-many-values-to-unpack-solution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!