Reputation: 17
When I try to save the file lines in a list I with the following code I get the below error:
Traceback (most recent call last):
File "C:\Users\emiel\AppData\Roaming\Sublime Text 3\Packages\User\Making_a_list_from_file.py", line 7, in <module>
with filename as file_object:
AttributeError: __enter__
This is the code:
with filename as file_object:
lines=file_object.readlines()
for line in lines:
print(line.strip())
Upvotes: 1
Views: 8200
Reputation: 104722
The error is telling you that the object you're using in the with
statement is not of the right type. __enter__
is one of the methods called as part of the context manager protocol, and the type you're using doesn't have that method.
Based on your variable name, it looks like you may be using a file name where you want to be using a file object. The error message will then make sense, as strings are not context managers the way file objects are. Try changing your with
statement to:
with open(filename) as file_object:
Upvotes: 4