ValueError: not enough values to unpack (expected 2, got 1) - I get this error once a file has been moved from one place to another

ValueError: not enough values to unpack (expected 2, got 1) - I get this error once a file has been moved from one place to another

我尝试编写一个脚本,根据我对文件的命名将文件从一个文件夹移动到多个文件夹。

例如,为了整理我的笔记,'Physics - a' 将从 'ts' 文件夹移动到“/Physics/Assignments”。

这在后台持续运行,并在将某些内容放入 'ts' 文件夹时为这些文件分配新位置。

我的脚本可以运行,但是在分配两个文件后,我收到以下错误

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

我不明白为什么会这样,也不明白如何解决。

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)

name 不包含破折号 (-)。您正在尝试按 - 拆分,左侧分配给单独的变量,右侧分配给另一个变量。在拆分之前,您应该检查 name 是否包含 -

当您像这样分配两个变量时:

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

Python 期望右侧部分包含两个值。这就是为什么它说:

not enough values to unpack (expected 2)

它需要两个值。您可能试图拆分一个没有 - 符号的文件名,因为 Python 在拆分后只收到一个值。这就是为什么它说:

(expected 2, got 1)

第 14 行,

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

需要一个包含两个元素的元组,第一个分配给代码,第二个分配给添加。当你 运行 进入错误时,name 必须设置为一个没有 '-' 的值,所以拆分命令 returns 一个单一的值。

问题: name 中的某些值中没有 -。因此,name.split('-') 会 return 一个只有一个项目的列表。当您将该列表分配给两个变量时,您的代码将如下所示:

name,ext = ['some name']

如您所见,python 没有获得足够的值来分配,它抛出 ValueError: not enough values to unpack (expected 2, got 1)

解决方法:检查name只包含一个-。如果包含多个-,则会抛出ValueError: too many values to unpack (expected 2)