roy roy - 21 days ago 7
Python Question

split - ValueError: need more than 1 value to unpack

I am reading a text file which has data in this format:

column : row


This is some sample data:

Name of the Property : North Kensington Upcycling Store and Cafe
Availability : Now
Interest Level : 74 people are looking right now
Area : 1,200 sqft
Retail Type : No
Bar & Restaurant Type : No


My code gives this error:

ValueError: need more than 1 value to unpack


at this line:

k,v = txt_line.split(":")


My code:

import pandas
txt_file = r"patty.txt"
txt = open(txt_file, "r")
txt_string = txt.read()
txt_lines = txt_string.split("\n")
txt_dict = {}

for txt_line in txt_lines:
print(txt_line)
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if k in txt_dict:
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
print (pandas.DataFrame.from_dict(txt_dict, orient="index"))

Answer

If a line of the input file is empty or missing the colon, split returns only 1 element and you get that error.

To play it safe, I would do a size check to avoid the exception, and print an explicit message when parsing is not possible (I added empty line skip to avoid crashing in that case)

if txt_line.strip():
   # line is not empty or just blanks
   toks = txt_line.split(":")
   if len(toks)==2:
       # unpack safely
       k,v = toks
   else:
       print("unable to parse {}".format(txt_line))