title: Python - Error with writing into a file opened in binary mode
body: <p>I'm trying to write a server-client program where the client reads from a file opened in binary mode and then sends it to the server which writes the data into another file in binary mode ('wb+'). </p>
  
  <p>The main part of the code where the error occurs is:</p>
  
  <pre><code>print(fileData)
  newFile.write(fileData)
  </code></pre>
  
  <p>And the output from this is:</p>
  
  <pre><code>b'Hello World!\n'
  Traceback (most recent call last):
  
    File "ftps.py", line 37, in &lt;module&gt;
  
      newFile.write(fileData)
  
  TypeError: a bytes-like object is required, not 'str'
  </code></pre>
  
  <p>Now I think I understand what the error is. The b'Hello World!\n' is of type string and must be in binary format before i can write it to the file. So I tried using fileData[2:-1].encode('utf-8') in order to convert it to binary object but it still wouldn't let me write into the text file. (The error no longer shows up but nothing gets written into the file. Is there some other way to do this or am I on the right path (trying to convert the string into a binary object?). Thanks!</p>
  
  <p>Edit: Sorry for not being clear the first time around but I don't specifically need to write the "hello world" string but just gave it as an example. The actual code has these 2 lines in a while loop and keeps printing different strings. And I'm using Python 3!</p>