Python Json with returns AttributeError: __enter__

半世苍凉 提交于 2019-12-14 03:45:47

问题


Why does this return AttributeError: __enter__

Sorting method is just a string created based on how the list is sorted, and current time uses 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)

Full traceback:

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

回答1:


You just for got to use 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)


来源:https://stackoverflow.com/questions/46273154/python-json-with-returns-attributeerror-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!