简体   繁体   中英

How to copy a .bin file to a text file in Python

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 :

with open('myfile.bin','r') as fileToCopy:

I got an error messages

'charmap' codec can't decode byte 0x90 in position 192:chatacter maps to <undefined>

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

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

and the .bin file contains lines like this:

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

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:

'utf-8' codec can't decode byte 0xfa in position 1:invalid start bye

The code that I used to decode to 'utf-8 format is :

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

Am I doing something wrong ? Is there another way to do this ?

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

Assuming it's your goal to copy the file myfile.bin to newfile.txt you might have a look at the module shutil from the Python standard library. This contains high-level file operations such as copy , move , delete and more.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM