问题
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