How to copy a .bin file to a text file in Python
<p>I'm trying to take a file with .bin suffix, encode it and then to send it to someone(sending it as .bin is not supported)...the problem is that when i use the command :</p>

<pre><code>with open('myfile.bin','r') as fileToCopy:
</code></pre>

<p>I got an error messages </p>

<pre><code>'charmap' codec can't decode byte 0x90 in position 192:chatacter maps to &lt;undefined&gt;
</code></pre>

<p>So i thought about a workaround which is converting the file to .txt and then to send it.
I tried to copy a binary file to a text file, the code that I used is</p>

<pre><code>with open('myfile.bin','rb') as fileToCopy:
    with open('newfile.txt,'w') as myNewFile:
        for line in fileToCopty:
            myNewFile.write(line)
</code></pre>

<p>and the .bin file contains lines like this:</p>

<pre><code>244e 504b 0100 3900 9000 0003 0100 0000
8000 0003 0200 0000 a432 0002 0000 0000
0002 0a02 0103 0000 0001 0a02 0003 0000
0001 0a02 0103 0000 0002 0a02 0003 0000
</code></pre>

<p>But the results are a file containing rubbish.
I tried also to decode the bytes as utf-8 format but i got this error message:</p>

<pre><code>'utf-8' codec can't decode byte 0xfa in position 1:invalid start bye
</code></pre>

<p>The code that I used to decode to 'utf-8 format is :</p>

<pre><code>with open('myfile.bin','rb') as fileToCopy:
    with open('newfile.txt,'w') as myNewFile:
        for line in fileToCopty:
            myNewFile.write(line.decode('utf-8'))
</code></pre>

<p>Am I doing something wrong ? Is there another way to do this ?</p>

<p>It's not clear what you are trying to do. Either you are trying to copy an existing file <code>myfile.bin</code> to a new file <code>newfile.txt</code> or you're trying to convert the binary file to a human readable format.</p>

<p>Assuming it's your goal to copy the file <code>myfile.bin</code> to <code>newfile.txt</code> you might have a look at the module <a href="https://docs.python.org/3/library/shutil.html" rel="nofollow">shutil</a> from the Python standard library. This contains high-level file operations such as <code>copy</code>, <code>move</code>, <code>delete</code> and more.</p>

<p>If it's your goal to decode the content of the file into a human readable format and your only information about the file is its <code>.bin</code> ending you might have a problem. The binary file could encode any information such as images, texts or videos. Without knowing the type of the encoding the content is more or less useless to you.</p>

python file text binary bin