What is the need for this variable in this loop?

Asked

Viewed 42 times

0

I made a simple program in Python that renames with a random number all the files in the folder in which the program file is. After some attempts and mistakes, I noticed in some examples of the internet that in the loop that did the "reading" of the files had a variable more than the loop that I had thought. Can anyone tell me the use of it?

In this case here is the variable x

import os, random
dirs = os.listdir(".")

for x, file in enumerate(dirs):    
    src = file
    newName = str(random.randint(1, 1000000))
    os.rename(src, newName)

But when I remove this variable...

import os, random
dirs = os.listdir(".")

for file in enumerate(dirs):    
    src = file
    newName = str(random.randint(1, 1000000))
    os.rename(src, newName)

... gives the following error:

TypeError: rename: src should be string, bytes or os.PathLike, not tuple

1 answer

2


The method enumerate returns an eternal object.
When you do the enumerate from a list, by going through this list you access tuples with 2 elements.

In its second code, the loop variable file is something of the format (index, file_name), and as the method rename takes a string as the first parameter, the error occurs because you are passing a tuple and not string type object.

In the first code, when decomposing

for x, file in enumerate(dirs)

The first variable x receives the first element of the tuple ( index ) and the variable file receives the second element ( file_name ) of the tuple generated by the method enumerate.

As in no time you use the variable x, the method is not required enumerate, the method os.listdir already returns an eternal list.

import os, random
dirs = os.listdir(".")

for file in dirs:    
    src = file
    newName = str(random.randint(1, 1000000))
    os.rename(src, newName)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.