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
Understanding Early Stopping: A Key to Preventing Overfitting in Machine Learning
About Deutsche Bank
Barstool Sports Gif
Www.1Tamilmv.cafe
Chris Provost Daughter Addie
Craigslist Free En Dallas Tx
Stadium Seats Near Me
Is pickleball Betts' next conquest? 'That's my jam'
Mama's Kitchen Waynesboro Tennessee
When Is the Best Time To Buy an RV?
Does Publix Have Sephora Gift Cards
Lonadine
Crossword Nexus Solver
WEB.DE Apps zum mailen auf dem SmartPhone, für Ihren Browser und Computer.
Water Days For Modesto Ca
Aspen Mobile Login Help
Lcwc 911 Live Incident List Live Status
Ruse For Crashing Family Reunions Crossword
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Raw Manga 1000
Www Pointclickcare Cna Login
Publix Near 12401 International Drive
Narragansett Bay Cruising - A Complete Guide: Explore Newport, Providence & More
Stickley Furniture
Osrs Important Letter
Happy Shuttle Cancun Review
Bridgestone Tire Dealer Near Me
Restaurants Near Calvary Cemetery
Http://N14.Ultipro.com
Microsoftlicentiespecialist.nl - Microcenter - ICT voor het MKB
Naya Padkar Newspaper Today
Austin Automotive Buda
Elgin Il Building Department
Studio 22 Nashville Review
Soulstone Survivors Igg
Trizzle Aarp
Google Flights Orlando
התחבר/י או הירשם/הירשמי כדי לראות.
Emily Browning Fansite
Fool's Paradise Showtimes Near Roxy Stadium 14
Yale College Confidential 2027
What is 'Breaking Bad' star Aaron Paul's Net Worth?
From Grindr to Scruff: The best dating apps for gay, bi, and queer men in 2024
The Many Faces of the Craigslist Killer
Premiumbukkake Tour
Stoughton Commuter Rail Schedule
116 Cubic Inches To Cc
Spn 3464 Engine Throttle Actuator 1 Control Command
Buildapc Deals
Overstock Comenity Login
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.