os.walk Value Error?

T

tdahsu

Hi,

I'm using os.walk as follows:

(basedir, pathnames, files) = os.walk("results", topdown=True)

and I'm getting the error:

ValueError: too many values to unpack

From my googling, that means:

This is the standard message when Python tries to unpack a tuple
into fewer variables than are in the tuple.

From what I can see of the examples on the python site, I'm using it
correctly. I have commas in my original code, and the "results"
directory exists and is directly under the directory from which my
script is run.

I'm assuming that 12 files (the number of files in the "results"
directory) is not too many for Python to handle! ;-)

Is there any other reason I might get that error?
 
C

Christian Heimes

Is there any other reason I might get that error?

Yes, you are using it the wrong way. The correct way is

for root, dirs, files in os.walk(path):
do something

os.walk returns an iterator which yields root, dirs and files for each
iteration.

Christian
 
T

tdahsu

os.walk is a generator so you need to make it a loop target:

for basedir, pathnames, files in os.walk("results"):
     #
     # Do you work inside the loop
     #

-Larry

Thanks!
 
G

Gabriel Genellina

I'm using os.walk as follows:

(basedir, pathnames, files) = os.walk("results", topdown=True)

and I'm getting the error:

ValueError: too many values to unpack


This is the standard message when Python tries to unpack a tuple
into fewer variables than are in the tuple.

correctly. I have commas in my original code, and the "results"
directory exists and is directly under the directory from which my
script is run.

Look the examples more carefully again - they don't use an assignment, but another Python statement...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,108
Latest member
AlbertEste
Top