user12498867
user12498867

Reputation: 11

Python ValueError: not enough values to unpack (expected 2, got 1)

In my text file i have Strings data i am try to unpack them using Split() but unfortunately giving me error as "ValueError: not enough values to unpack (expected 2, got 1)" Plz help to solve me if you know

with open('Documents\\emotion.txt', 'r') as file:
    for line in file:
        clear_line = line.replace("\n", '').replace(",", '').replace("'", '').strip()
        print(clear_line)
        word,emotion = clear_line.split(':')

I have this type of data

victimized: cheated
accused: cheated
acquitted: singled out
adorable: loved
adored: loved
affected: attracted
afflicted: sad
aghast: fearful
agog: attracted
agonized: sad
alarmed: fearful
amused: happy
angry: angry
anguished: sad
animated: happy
annoyed: angry
anxious: attracted
apathetic: bored

Upvotes: 1

Views: 10124

Answers (2)

Red
Red

Reputation: 27567

That error can be caused if you have any empty lines in your file, because you're telling python to unpack [''] into word, emotion. To fix the problem, you can add an if statement like this:

with open('Documents\\emotion.txt', 'r') as file:
    for line in file:
        if line:
            clear_line = line.replace("\n", '').replace(",", '').replace("'", '').strip()
            print(clear_line)
            word,emotion = clear_line.split(':')

if line: means if the line is not empty.

Upvotes: 0

Astik Anand
Astik Anand

Reputation: 13047

It is happening because of more than 1 empty lines at the end of file. Rest of your code is working fine.

You can do below to avoid the error.

if not clear_line:
    continue

word, emotion = clear_line.split(':')

Upvotes: 1

Related Questions