python - 将数组中的 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:
。如何将数组转换为类似字节的对象?
解决方案
您可以直接编写字符串,无需将其转换为字节。尝试
with open(output_dir + "output.csv", "w") as f:
文件模式:
wb: write byte
rb: read byte
w: write
r: read
a: append
推荐阅读
- r - 在 R 的 quantmod 包中使用 SMA() 函数时出错
- colors - 无法在 Zsh 中使用颜色;文字有效,但没有颜色出现
- css - 如何设置样式以在 div 内显示输入搜索框
- python - 为什么我的 pandas 中的数据框列不会从浮点数转换为整数?
- python - 如何在不随机重叠数字的情况下按升序打印 6 个数字?
- reactjs - Herokuapp 无法连接到后端 api
- android - 哪个是有效的->通过drawLine()绘制4条线以制作一个矩形或通过drawRect()直接绘制一个矩形
- excel - DAX 度量以根据不同的月值创建每日目标
- react-native - 使用状态数组。ERROR 错误:重新渲染过多。React 限制渲染次数以防止无限循环
- java - Okhttpclient 得到错误响应