+5 votes
in Programming Languages by (71.8k points)

I am using the following code to write data to a gzipped file, but it is giving an error: TypeError: memoryview: a bytes-like object is required, not 'str'. What's wrong with the code?

# Write the header

ofile = gzip.open(outfile, "wb")

hdr = "mv" + "\t" + "predicted_prob" + "\t" + "true_label" + "\n" 

ofile.write(hdr)

1 Answer

+2 votes
by (350k points)
selected by
 
Best answer

You have opened the file in binary mode and are trying to write text to the file. That's why it is giving error.

Change "wb" to "wt" if you want to write text data.

Here is the modified code:

# Write the header

ofile = gzip.open(outfile, "wt")

hdr = "mv" + "\t" + "predicted_prob" + "\t" + "true_label" + "\n" 

ofile.write(hdr)


...