Search code examples
pythonfor-loopvalueerror

Can someone explain what ValueError: not enough values to unpack (expected 2 , got 1) actually means and how to fix it?


I was making a script that renames files in a given directory into "CoronaVirus" and when testing it I noticed that it only does it in the given directory and not in it's subfolders. The code looks something like this(note: this one works):

import os

PRF = input("Input Directory: ")

def main():

for file in PRF:
    for filename in os.listdir(PRF):
          i = 0
          dst = "CoronaVirus" + str(i)
          src = PRF + filename
          dst = PRF + dst
          os.rename(src , dst)
          i += 1
if __name__ == "__main__"":
    main()

After I saw that it only goes through the given directory I tried adding a new statement(forgive me if that's not what it is called) called subdir thinking that it would make it look throuh folders. That made the code look like this:

import os

PRF = input("Input Directory: ")

def main():

for subdir , file in PRF:
    for filename in os.listdir(PRF):
           i = 0
           dst = "CoronaVirus" + str(i)
           src = PRF + filename
           dst = PRF + dst
           os.rename(src , dst)
           i += 1
if __name__ == "__main__"":
    main()

But this doesn't seem to work as it gives this error:

Traceback (most recent call last):
File "C:/Users/Acer/Desktop/Python/Pyinstaller/OSM.py", line 17, in <module>
main()
File "C:/Users/Acer/Desktop/Python/Pyinstaller/OSM.py", line 7, in main
for  subdir , file in PRF:
ValueError: not enough values to unpack (expected 2, got 1)

Can somebody explain why this is happening? I'm a beginner and would like to avoid this issue in the future. Thanks!


Solution

  • If you want it to go through the current directory and all subdirectories I would use os.walk

    I'm not sure exactly what order this will go through the files but at least it will go through them all.

    I also had to remove the i=0 from the loop and add something that ensures the extension is kept

    If there are zip files, you probably should extract these into the folder first as this won't look in them and would instead name the zip folder 'CoronaVirusN.zip'

    I put in an if to exclude zip files

    PRF = 'C:\\Users\\ALi\\OneDrive\\StackOverflow\\Test'
    
    i = 0
    for subdir, dirs, files in os.walk(PRF):
        for file in files:
            extension = file.split('.')[1]
            if extension != 'zip':
                dst = "CoronaVirus" + str(i) + '.' + extension
                src = subdir + '\\' + file
                dst = subdir + '\\' + dst
                os.rename(src , dst)
                i += 1