【问题标题】:Python Json with returns AttributeError: __enter__带有返回 AttributeError 的 Python Json:__enter__
【发布时间】:2018-02-26 15:04:53
【问题描述】:

为什么会返回 AttributeError: __enter__

排序方法只是根据列表的排序方式创建一个字符串,当前时间使用stfttime

current_time = strftime("%Y-%m-%d %H-%M-%S", gmtime())

filename = f"Komplett-{str(sorting_method)}-{str(current_time)}.txt"
if not os.path.exists(f'C:/Users/tagp/OneDrive/Dokumenter/Python/{filename}'):
        open(str(filename), "w+")   
with (filename, "w+") as json_data:
            my_list = {}
            my_list["products"] = []
            for thing in my_products:
                my_list["products"].append({
                    "Product Title":thing.title,
                    "Price":thing.price,
                    "Rating":thing.rating,
                    "Stock":thing.stock
                    })
            json.dump(my_list, json_data, indent = 4)

完整的追溯:

Traceback (most recent call last):
    File "komplett.py", line 172, in <module>
        with (filename, "w") as json_data:
AttributeError: __enter__

【问题讨论】:

  • 你能发布完整的回溯
  • 已编辑的帖子带有完整的追溯
  • 你忘记了open
  • 就是这样!谢谢

标签: python json python-3.x attributeerror


【解决方案1】:

你只是为了使用 open

current_time = strftime("%Y-%m-%d %H-%M-%S", gmtime())

filename = f"Komplett-{str(sorting_method)}-{str(current_time)}.txt"
if not os.path.exists(f'C:/Users/tagp/OneDrive/Dokumenter/Python/{filename}'):
        open(str(filename), "w+")   
with open(filename, "w+") as json_data:
            my_list = {}
            my_list["products"] = []
            for thing in my_products:
                my_list["products"].append({
                    "Product Title":thing.title,
                    "Price":thing.price,
                    "Rating":thing.rating,
                    "Stock":thing.stock
                    })
            json.dump(my_list, json_data, indent = 4)

【讨论】:

  • 欢迎您,也不要忘记在发布问题时发布回溯。社区同行解决问题会更容易
  • 我认为它可能有点容易理解它的内容,因为它很短。不过我的错误下次会记住这一点
猜你喜欢
  • 2022-08-16
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多