【问题标题】:Converting str to byte from an array and save it to CSV (in Python)将字符串从数组转换为字节并将其保存为 CSV(在 Python 中)
【发布时间】:2021-03-10 10:56:03
【问题描述】:

我想将数组中的 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: 时运行。 如何将数组转换为类似字节的对象?

【问题讨论】:

    标签: python arrays binary


    【解决方案1】:

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

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

    文件模式:

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

    【讨论】:

    • 工作正常,但我希望最后是二进制 CSV
    • 如果你想写字节,那么你将不得不使用encode,但它不适用于np.savetext。你为什么要写字节?阅读时始终可以读取字节
    • 用你自己的话来说什么是“二进制 CSV”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多