Python - Write Bytes to File - GeeksforGeeks (2024)

Last Updated : 15 Sep, 2022

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps:

  1. Open file
  2. Perform operation
  3. Close file

There are four basic modes in which a file can be opened― read, write, append, and exclusive creations. In addition, Python allows you to specify two modes in which a file can be handled― binary and text. Binary mode is used for handling all kinds of non-text data like image files and executable files.

Write Bytes to File in Python

Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.

Python3

some_bytes = b'\xC3\xA9'

# Open in "wb" mode to

# write a new file, or

# "ab" mode to append

with open("my_file.txt", "wb") as binary_file:

# Write bytes to file

binary_file.write(some_bytes)

Output:

Python - Write Bytes to File - GeeksforGeeks (2)

my_file.txt

Example 2: This method requires you to perform error handling yourself, that is, ensure that the file is always closed, even if there is an error during writing. So, using the “with” statement is better in this regard as it will automatically close the file when the block ends.

Python3

some_bytes = b'\x21'

# Open file in binary write mode

binary_file = open("my_file.txt", "wb")

# Write bytes to file

binary_file.write(some_bytes)

# Close file

binary_file.close()

Output:

Example 3: Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below.

Python3

# Create bytearray

# (sequence of values in

# the range 0-255 in binary form)

# ASCII for A,B,C,D

byte_arr = [65,66,67,68]

some_bytes = bytearray(byte_arr)

# Bytearray allows modification

# ASCII for exclamation mark

some_bytes.append(33)

# Bytearray can be cast to bytes

immutable_bytes = bytes(some_bytes)

# Write bytes to file

with open("my_file.txt", "wb") as binary_file:

binary_file.write(immutable_bytes)

Output:

Python - Write Bytes to File - GeeksforGeeks (4)

my_file.txt

Example 4: Using the BytesIO module to write bytes to File

Python3

from io import BytesIO

write_byte = BytesIO(b"\xc3\x80")

with open("test.bin", "wb") as f:

f.write(write_byte.getbuffer())

Output:

Python - Write Bytes to File - GeeksforGeeks (5)

test.bin



Please Login to comment...

Python - Write Bytes to File - GeeksforGeeks (2024)
Top Articles
Radeon RX 580 8GB GDDR5 OC 5M (3x DP, HDMI, DL-DVI) OVERCLOCKED EDITION
Debt Relief and Debt Relief Scams
No Hard Feelings (2023) Tickets & Showtimes
Top 11 Best Bloxburg House Ideas in Roblox - NeuralGamer
Valley Fair Tickets Costco
Crocodile Tears - Quest
Nwi Police Blotter
Tx Rrc Drilling Permit Query
Mohawkind Docagent
10000 Divided By 5
Toonily The Carry
What Does Dwb Mean In Instagram
Caroline Cps.powerschool.com
New Mexico Craigslist Cars And Trucks - By Owner
C Spire Express Pay
Shreveport Active 911
Busted Barren County Ky
Wisconsin Women's Volleyball Team Leaked Pictures
Forum Phun Extra
Walgreens Tanque Verde And Catalina Hwy
Concordia Apartment 34 Tarkov
Zack Fairhurst Snapchat
Program Logistics and Property Manager - Baghdad, Iraq
Walmart Near South Lake Tahoe Ca
Disputes over ESPN, Disney and DirecTV go to the heart of TV's existential problems
Silky Jet Water Flosser
Best Middle Schools In Queens Ny
Dmv In Anoka
Lindy Kendra Scott Obituary
Jail Roster Independence Ks
Ridge Culver Wegmans Pharmacy
Melissa N. Comics
Xfinity Outage Map Lacey Wa
The Venus Flytrap: A Complete Care Guide
Cars And Trucks Facebook
Breckie Hill Fapello
Trebuchet Gizmo Answer Key
The Thing About ‘Dateline’
Walgreens Agrees to Pay $106.8M to Resolve Allegations It Billed the Government for Prescriptions Never Dispensed
159R Bus Schedule Pdf
World Social Protection Report 2024-26: Universal social protection for climate action and a just transition
Letter of Credit: What It Is, Examples, and How One Is Used
Tom Kha Gai Soup Near Me
Hillsborough County Florida Recorder Of Deeds
Unblocked Games 6X Snow Rider
Pelican Denville Nj
2487872771
Mkvcinemas Movies Free Download
Service Changes and Self-Service Options
Bomgas Cams
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 5882

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.