[Solved] Python Error: TypeError: write() argument must be str, not bytes

In the chapter “decision tree” of “machine learning in action”, the error typeerror: write() argument must be STR, not bytes is first prompted in the stored procedure of learning decision tree. The error message is that the parameter of write() function must be STR, not byte. I don’t understand. Look at the source code. There is an error. There is an error in compiling the sentence pickle. Dump (inputtree, FW). Let’s first look at the usage of pickle. Dump()

From the penultimate sentence, we can see that our problem lies in the variable FW, that is, the statement FW = open (file name, ‘W’). That is to say, the type of the variable FW should be bytes, so you can change ‘W’ to ‘WB’ and compile it successfully after modification. The same principle prompts Unicode decodeerror: ‘GBK’ codec can’t decode byte 0x80 in position 0: illegal multibyte sequence error, because the previously saved TXT file is written in binary, so binary should also be used when reading, Fr = open (filename) in the read file should be changed to fr = open (filename, ‘RB’). OK, problem solved! Under the test:

success!

Read More: