roy roy - 1 year ago 195
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_lines = txt_string.split("\n")
txt_dict = {}

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

Answer Source

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
       print("unable to parse {}".format(txt_line))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download