簡體   English   中英

Python:AttributeError:“設置”對象沒有屬性“格式”

[英]Python: AttributeError: 'set' object has no attribute 'format'

我正在嘗試下面的代碼,並且彈出屬性錯誤。 我是Python的新手,很高興知道我可以做些什么來糾正此錯誤。

    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'

在python中,使用大括號(寫了{0} )是用來創建一個內置對象(稱為集合)。 一個集合(就像在數學中一樣)是一個無序的唯一元素集合,並且無法格式化,因此沒有set.format方法,當您嘗試在集合上調用format方法時會導致屬性錯誤: {0}.format(..)

您可能是說:

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

這將創建一個字符串,該字符串具有格式方法,因此應該可以使用。

使用種姓類型,替換您的這一行,

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

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

現在您可以將其格式化為“ utf-8”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM