我正在尝试生成Mandelbrot集并将转储图像保存在目录.py文件中
import math
width = 640
height = 480
image = [[[255 for c in range(3)] for x in range(width)] for y in range(height)]
for y in range(height):
imag = (y-(height/2)) / float(height)*2.5
for x in range(width):
real = ((x-(width/2)) / float(width)*2.5)-0.5
z = complex ( real, imag )
c = z
for i in range(255):
z = z*z + c
if ( abs(z)>2.5 ):
image[y][x]=[i,i,i]
break
output = open ( 'mandelbrot_set.ppm', 'w' )
output.write("P6 " + str(width) + " " + str(height) + " 255\n")
for y in range(height):
for x in range(width):
output.write(bytearray(image[y][x]))
output.close()
预期的输出是在目录中设置的mandelbrot的图像,我在该文件中确实得到了一个文件,但是它什么也没有显示,并且终端中出现错误,如下所示:
Traceback (most recent call last):
File "mandelbrot.py", line 21, in <module>
output.write(bytearray(image[y][x]))
TypeError: write() argument must be str, not bytearray
答案 0 :(得分:1)
如果要将二进制数据写入文件,则必须以 binary模式打开它:
output = open ( 'mandelbrot_set.ppm', 'wb' )
但是,在这种情况下,您将无法编写文本,因此该行:
output.write("P6 " + str(width) + " " + str(height) + " 255\n")
将引发错误。您应该对这样的字符串进行编码:
output.write(("P6 " + str(width) + " " + str(height) + " 255\n").encode())
这将使用指定的编码将字符串转换为字节数组(bytes
对象),默认情况下为utf-8
。