'Problem to convert act format to CSV a bytes-like object is required, not 'str'
I have a problem converting an .act file to csv format. I am using this code:
import struct
import csv
DATA = []
with open("modis_lst.act", "rb") as actFile:
for _ in range(256):
raw = actFile.read(3)
color = struct.unpack("3B", raw)
DATA.append(color)
with open('test.csv', 'wb') as csvfile:
csvWriter = csv.writer(csvfile)
csvWriter.writerows(DATA)
but I get the following ERROR: a bytes-like object is required, not 'str'
Solution 1:[1]
I mocked up what I think you're working with:
import struct
import csv
DATA = []
raw = struct.pack("3B", 255, 0, 0)
color = struct.unpack("3B", raw)
DATA.append(color)
with open("test.csv", "wb") as csvfile:
csvWriter = csv.writer(csvfile)
csvWriter.writerows(DATA)
and I too get:
File "/users/z/main.py", line 15, in <module>
csvWriter.writerows(DATA)
TypeError: a bytes-like object is required, not 'str'
And this is because opening the file as binary (wb
) is wrong in this case: you've already decoded the binary structure into strings, so open the file as plain text and pass that to the CSV writer:
with open("test.csv", "w") as csvfile:
and now my test.csv file looks correct:
255,0,0
P.S. I don't know when opening a file as binary for writing CSV is correct... I've never thought of that before :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zach Young |