Search code examples
pythonstringwhile-loopsplititerable-unpacking

ValueError: not enough values to unpack (expected 2, got 1) when splitting strings


I've tried to write a script that moves files from one folder to a selection of folders depending on what I have named the file.

For example, 'Physics - a' would be moved from the 'ts' folder to '/Physics/Assignments' in an effort to organize my notes.

This runs continuously in the background and allocates these files new homes the moment that something is placed into the 'ts' folder.

My script works, but after allocating two files, I get the following error:

line 14, add = name.split('-') ValueError: not enough values to unpack (expected 2, got 1).

I don't understand why this occurs, nor how to fix it.

import os
import time
from datetime import date

def clean():

    os.chdir('/Users/Chadd/Desktop/ts')

    i = 0
    while i < len(os.listdir()):
        i = 0
        
        name, ext = os.path.splitext(os.listdir()[i])
        code, add = name.split('-')
        folder = code.strip().upper()

        if add.strip() == 'a':
            add = 'Assignments'

        if add.strip() == 'p':
            add = 'Past Papers'

        if add.strip() == 'n':
            add = 'Notes'

        if add.strip() == 't':
            add = 'Tutorials'

        today = date.today()

        os.rename(
        '/Users/Chadd/Desktop/ts/{}'.format(os.listdir()[i]),
        '/Users/Chadd/Desktop/{}/{}/{}'.format(folder, add, folder + ' - ' + add[:-1] + ' (' + str(today) + ')' + ' - ' + str(1 + len(os.listdir('/Users/Chadd/Desktop/{}/{}'.format(folder, add.strip())))) + ext)
         )

        if len(os.listdir()) == 0:
            break

while True:
    clean()
    time.sleep(1)

Solution

  • When you assign two variables like this:

    code, add = name.split('-')

    Python expects the right-hand part to contain two values. That's why it said:

    not enough values to unpack (expected 2)

    It expected two values. You probably tried to split a filename that had no - symbol, because Python received only one value after the split. That's why it said:

    (expected 2, got 1)