Python help: writing to a file with pickle

So I’m trying to write a float object to a file using pickle. This is the code:


GD = globalDict

GD['posX'] = 0.0
file = open(filepath, 'r+')
pickle.dump(GD['posX'], file) 

Then it gives me this error on the last line: TypeError: must be str, not bytes
I thought pickle.dump accepted an Object and a File as arguments, so I don’t know what I’m doing wrong.

This is true, however you’ve received the error after writing to a file with bytes, when you requested a string protocol. Change “r+” to “rb”

Thank you! It seems kind of silly that there’s a distinction between writing bytes and writing a string.

At first that is a valid assumption, however in reality they are two different data types. Rather than determining how you write your data automatically, it will throw an error if you do something wrong. There used to be something called “coercion” in Python where different data types could be converted to others if they needed to be, but that is rather bad practice as it is implicit. Now we do it explicitly, and rarely because it is bad practice to coerce.

The main reason is to do with how the operating system deals with null characters in strings. On some operating system if you were to try to write a byte array with multiple null characters to a file opened for ascii I/O, it would either truncate the input at the first null character, or just ignore null characters completely. What you end up with is a file that does not contain what you wrote to it.

Similarly, if you opened a file for binary reading, but treated the data like a string, it could potentially lead to buffer overflows and memory leaks and all sort of other nastiness.

Python’s file I/O is just a thin layer of abstraction over the c syscalls… just a little side trivia…