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.
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…