roy roy - 19 days ago 6
Python Question

Python - Value Error : - need more than 1 value to unpack

I have a text file which has the data in the form of column : row. I would like to load this text file into python and convert it into csv or an excel file and save it in local desktop. Anyone have a logic? Kindly share your answers. Thanks in advance. Here goes a sample of my data in the text file [ kindly see that Price per Quarter is missing in the second set of 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
Event Type : Yes
Shop Share Type : No
Unique Type : No
Price Per Day : £360
Price Per Week : £1,260
Price Per Month : £5,460
Price Per Quarter : £16,380
Price Per Year : £65,520
[Latitude, Longitude] : [51.5235108631773, -0.206594467163086]
Name of the Property : Old Charlton Pub
Availability : Now
Interest Level : 20 people are looking right now
Area : 1,250 sqft
Retail Type : No
Bar & Restaurant Type : Yes
Event Type : No
Shop Share Type : No
Unique Type : No
Price Per Day : £70
Price Per Week : £490
Price Per Month : £2,129
Price Per Year : £25,550
[Latitude, Longitude] : [51.4926332979245, 0.0449645519256592]


This is the code that I am trying,

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"))


and getting this error :- k,v = txt_line.split(" : ") ValueError: need more than 1 value to unpack

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))
Comments