Python: AttributeError: 'set' object has no attribute 'format'

i am trying out the code below and the attribute error popped up. I am new to Python and would appreciate to know what I can do to correct this error.

 with open(csv_file_path,'wb+') as fout: csv_file = csv.writer(fout) csv_file.writerow(list(column_names)) with open(json_file_path) as fin: for line in fin: line_contents = json.loads(line) csv_file.writerow(get_row(line_contents,column_names)) read_and_write_file(json_file,csv_file,column_names) if isinstance(line_value,unicode): row.append({0}.format(line_value.encode('utf-8')))
Traceback (most recent call last): File "Json_convert.py", line 89, in <module> read_and_write_file(json_file, csv_file, column_names) File "Json_convert.py", line 19, in read_and_write_file csv_file.writerow(get_row(line_contents,column_names)) File "Json_convert.py", line 62, in get_row row.append({0}.format(line_value.encode('utf-8')))
AttributeError: 'set' object has no attribute 'format'
3

2 Answers

In python, using curly brackets as you did (where you wrote {0}) is for creating an inbuilt object known as a set. A set is (like in mathematics) an un-ordered collection of unique elements, and is cannot be formatted, and hence there is no set.format method, leading to the attribute error when you tried to call the format method on a set: {0}.format(..).

You may have meant:

row.append("{0}".format(line_value.encode('utf-8')))

This creates a string, which does have a format method, so this should work.

use type caste, replace your this line,

row.append({0}.format(line_value.encode('utf-8')))

with

row.append({0}.format(str(line_value).encode('utf-8')))

and now you can format it to 'utf-8'

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like