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

Question:

In the following code:

file = input("Email LIST : ")
in_emails = open(file,'r',errors='ignore').read().splitlines()
    
    domain_set = set()
    
    out_emails = []
    
    for email in in_emails:
        _, tmp = email.split("@", maxsplit=1)
        domain, _ = tmp.split(":", maxsplit=1)
        if domain not in domain_set:
            out_emails.append(email)
            domain_set.add(domain)
    
    print(out_emails)

I am getting the error below:

_, tmp = email.split("@", maxsplit=1) ValueError: not enough values to unpack (expected 2, got 1) 

Any solution for ignoring wrong Lines ?

Asked By: S0o SiYa

||

Answers:

Make sure you are not passing any empty string to email.
If email doesn’t contain @ the split will always return a single value. And you can’t unpack (or assign) a single value into two variables.

_, tmp = "[email protected]".split("@", maxsplit=1) It works.

_, tmp = "randomemail".split("@", maxsplit=1) It will throw error.

For more information about split method, see here: python-split

Answered By: Arif Hosan

You can pave over anything that goes wrong and log it like this:

for email in in_emails:

    try:
        _, tmp = email.split("@", maxsplit=1)
        domain, _ = tmp.split(":", maxsplit=1)
        if domain not in domain_set:
            out_emails.append(email)
            domain_set.add(domain)
    except Exception as err:
        print(f"Failed to parse email '{email}'", err)
Answered By: kenny_k
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.