Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 导致此错误的原因是什么?如何修复?_Python_Python 3.x - Fatal编程技术网

Python 导致此错误的原因是什么?如何修复?

Python 导致此错误的原因是什么?如何修复?,python,python-3.x,Python,Python 3.x,我试图用Python编写一个简单的压缩程序,但收到了这个错误 with open("admin.dll", "r").read() as text: AttributeError: __exit__ 为什么我会犯这个错误?这是我的全部代码 import zlib, sys, time, base64 with open("admin.txt", "r").read() as file: print("Uncompressed: " + str(sys.getsizeof(fil

我试图用Python编写一个简单的压缩程序,但收到了这个错误

with open("admin.dll", "r").read() as text:
AttributeError: __exit__    
为什么我会犯这个错误?这是我的全部代码

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))

您要求Python将表达式openadmin.dll,r.read字符串的结果作为上下文管理器处理。上下文管理器应该有一个_退出_方法,但字符串没有这些方法

您通常会传入文件对象:

文件对象确实具有所需的上下文管理器方法


请注意,您还有其他错误;sys.getsizeof生成Python对象的内存大小,而不是文件大小。您可以使用,或者查找到文件末尾,然后使用fileobj.tell获取大小。要获得压缩结果的大小,请使用len。

我认为您应该打开该文件。为它指定一个变量。在你的案件档案中。 然后在下一行,您可以通过调用f.read来读取文件

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