首页 > 解决方案 > output.write(bytearray(image[y][x])) TypeError: write() 参数必须是 str,而不是 bytearray

问题描述

我正在尝试在目录中生成 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

标签: python-3.x

解决方案


如果要将二进制数据写入文件,则必须以二进制模式打开它:

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默认情况下的。


推荐阅读