Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Json with returns AttributeError: __enter__

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__
like image 350
Peebl Avatar asked Sep 18 '17 06:09

Peebl


1 Answers

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)
like image 77
Max Avatar answered Oct 10 '22 05:10

Max