How to Write Bytes to File in Python

To write bytes to a file in Python, you can create a file object in binary mode and then use the write() method of the file object.

Here’s an example of how to do it:

# Open the file in binary mode with open('file.bin', 'wb') as f: # Write the bytes to the file f.write(b'\x01\x02\x03')
Code language: PHP (php)

In this example, b'\x01\x02\x03' is a bytes object containing the bytes to be written to the file. The 'wb' mode opens the file in binary write mode, which allows you to write raw bytes to the file.

You can also write a string to a file by encoding it as bytes first, like this:

# Open the file in binary mode with open('file.txt', 'wb') as f: # Encode the string as bytes and write it to the file f.write('hello'.encode('utf-8'))
Code language: PHP (php)

In this example, the string 'hello' is encoded as a UTF-8 byte string and then written to the file.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *