Matt X Matt X - 23 days ago 3
Python Question

What is causing this error and how can I fix it?

I am trying to make a simple compression program in Python, but am receiving this error

with open("admin.dll", "r").read() as text:
AttributeError: __exit__


Why am I getting this error? This is my full code

import zlib, sys, time, base64
with open("admin.txt", "r").read() as file:
print("Uncompressed: " + str(sys.getsizeof(file)))
compressed = zlib.compress(file, 9)
print("Compressed: ", end="")
print(sys.getsizeof(compressed))

Answer

You are asking Python to treat the result of the expression open("admin.dll", "r").read() (a string) as a context manager. Context managers are expected to have a __exit__ method, but strings don't have those methods.

You'd normally pass in the file object:

with open("admin.dll", "r") as fileobj:
    text = fileobj.read()

File objects do have the required context manager methods.

Note that you have other errors too; sys.getsizeof produces the memory size of a Python object, not the size of a file. You could use os.stat() for that, or seek to the end of the file and use fileobj.tell() to get a size. To get the size of the compressed result, use len().

Comments