Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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 png文件错误的file.read()?_Python_File_Png - Fatal编程技术网

Python png文件错误的file.read()?

Python png文件错误的file.read()?,python,file,png,Python,File,Png,我正在尝试阅读纯文本的PNG图像,就像在记事本中一样。(用于以后转换为base64) 测试图像: 所以我尝试了以下代码: f = 'test1.png' with open(f) as file: for i in xrange(0, 5): print(i, f, file.read()) print f = 'test2.png' with open(f) as file: for i in xrange(0, 5): print(i, f,

我正在尝试阅读纯文本的PNG图像,就像在记事本中一样。(用于以后转换为base64)

测试图像:

所以我尝试了以下代码:

f = 'test1.png'
with open(f) as file:
    for i in xrange(0, 5):
        print(i, f, file.read())
print
f = 'test2.png'
with open(f) as file:
    for i in xrange(0, 5):
        print(i, f, file.read())
但它并没有读取整个文件,比如“读取”函数就是假定要做的。 如果我再次尝试调用
read
,对于某些PNG,它会读取更多部分,对于其他PNG,它不会读取,无论调用频率如何

我只有以下输出:

(0,'test1.png','\x89PNG\n')
(1,‘test1.png’,“”)
(2,‘test1.png’,“”)
(3,‘test1.png’,“”)
(4,‘test1.png’,“”)
(0,'test2.png','\x89PNG\n')
(1,'test2.png','\xd2y\xb4j|\x8f\x0b5MW\x98D\x97\xfc\x13\\7\x11\xcaPn\x18\x80,}\xc6g\x90\xc5n\x8cDi\x81\xf9\xbel\xd6Fl\x11\xae\xdf\xf0')
(2,‘test2.png’,“”)
(3,‘test2.png’,“”)
(4,‘test2.png’,“”)
但我希望它是这样的:

是虫子吗


在base64中获取此文件的任何其他(简单)方法?

PNG文件不是文本文件;您必须将其读取为二进制文件,而不是文本文件,如下所示:

with open(f, 'rb') as file:
如果要生成数据的base64编码,请使用
base64
模块:

import base64
f = 'test1.png'
with open(f) as file:
    for i in xrange(0, 5):
        print(i, f, base64.b64encode(file.read()))

你试过打开(f,'rb')?Thx,@TigerhawkT3。这是我们的工作!