+4 votes
in Programming Languages by (17.7k 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

0 votes
by (35.8k points)

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)

...