Python中使用Json时返回AttributeError: __enter__错误

6

为什么会返回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__

你能否发布完整的回溯信息? - Max
编辑了帖子,附上完整的回溯信息。 - Peebl
4
你忘记了加上 open - user2357112
就是这样!谢谢。 - Peebl
1个回答

8
你刚刚忘记使用“打开”命令。
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)

欢迎,同时在发布问题时不要忘记附上回溯信息。这将使社区同行更容易解决查询。 - Max
1
我想它可能很容易理解,因为它很短。但我的错误,下次会记住的。 - Peebl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接