python-3.x - 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
解决方案
如果要将二进制数据写入文件,则必须以二进制模式打开它:
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
默认情况下的。
推荐阅读
- c# - 计算并在文本框中显示最终值
- c - 如何使用 goto 进行这个 for 循环?
- javascript - 在 HTML 页面中显示 Javascript 对象的问题
- c# - 如何在 C# 中向游戏(进程)发送密钥
- python - 试图制作一个服务器机器人,但日期时间有问题,我不明白它是什么
- javascript - 弧形图在 Angular 项目中不起作用
- python - 如何尽可能准确地识别图像中的明亮区域?
- rxjs - 如何使用 RxJS 创建暂停/恢复计时器,它也计算中断时间
- flutter - Flutter:从类中获取共享偏好项到无状态小部件编辑#1
- c++ - 使用 clion 在 C++ 中连接 sqlite