首页 > 解决方案 > 将数组中的 str 转换为字节并将其保存为 CSV(在 Python 中)

问题描述

我想将数组中的 CSV 保存为二进制文件,但它不起作用。

我得到了这个代码:

    for item in directory:
        originalImage = cv2.imread(input_dir + item)
        grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)
        thresh = 128
        img_binary = cv2.threshold(grayImage, thresh, 255, cv2.THRESH_BINARY)[1]
        img_not = cv2.bitwise_not(img_binary)
        cv2.imwrite(output_dir + item[:-4] +'.png',img_not)

        if check_var1.get():
            with open(output_dir + "output.csv", "wb") as f:
                np.savetxt(f, img_binary,  fmt="%d", delimiter=",")
                f.write("\n")

我得到这个错误:

TypeError: a bytes-like object is required, not 'str'

该代码仅在我使用时运行with open(output_dir + "output.csv", "a") as f:。如何将数组转换为类似字节的对象?

标签: pythonarraysbinary

解决方案


您可以直接编写字符串,无需将其转换为字节。尝试

with open(output_dir + "output.csv", "w") as f:

文件模式:

wb: write byte
rb: read byte
w: write
r: read
a: append

推荐阅读