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
Facebook Marketplace Fees - How To Calculate Your Profits
A Crash Course on Microservice Communication Patterns
Katie Nickolaou Leaving
Whas Golf Card
Bank Of America Financial Center Irvington Photos
Duralast Gold Cv Axle
How to Type German letters ä, ö, ü and the ß on your Keyboard
Back to basics: Understanding the carburetor and fixing it yourself - Hagerty Media
Crime Scene Photos West Memphis Three
Shariraye Update
Hope Swinimer Net Worth
Signs Of a Troubled TIPM
Wnem Radar
Immediate Action Pathfinder
Echo & the Bunnymen - Lips Like Sugar Lyrics
Mini Handy 2024: Die besten Mini Smartphones | Purdroid.de
Belly Dump Trailers For Sale On Craigslist
Stihl Km 131 R Parts Diagram
Craigslist Farm And Garden Cincinnati Ohio
iOS 18 Hadir, Tapi Mana Fitur AI Apple?
Jesus Calling Oct 27
DoorDash, Inc. (DASH) Stock Price, Quote & News - Stock Analysis
Gdp E124
Vermont Craigs List
The Old Way Showtimes Near Regency Theatres Granada Hills
Wemod Vampire Survivors
Craigslist Apartments Baltimore
Www Va Lottery Com Result
Walgreens Bunce Rd
Craigslist Pennsylvania Poconos
Asteroid City Showtimes Near Violet Crown Charlottesville
Kitchen Exhaust Cleaning Companies Clearwater
UCLA Study Abroad | International Education Office
Craigslist Scottsdale Arizona Cars
Busted! 29 New Arrests in Portsmouth, Ohio – 03/27/22 Scioto County Mugshots
Ucm Black Board
How to Use Craigslist (with Pictures) - wikiHow
Http://N14.Ultipro.com
Consume Oakbrook Terrace Menu
Naya Padkar Newspaper Today
Hebrew Bible: Torah, Prophets and Writings | My Jewish Learning
Merkantilismus – Staatslexikon
Www Craigslist Com Brooklyn
Craigslist Putnam Valley Ny
Indiana Jones 5 Showtimes Near Cinemark Stroud Mall And Xd
Verizon Outage Cuyahoga Falls Ohio
Uc Davis Tech Management Minor
Interminable Rooms
Ajpw Sugar Glider Worth
Electric Toothbrush Feature Crossword
Hampton Inn Corbin Ky Bed Bugs
Koniec veľkorysých plánov. Prestížna LEAF Academy mení adresu, masívny kampus nepostaví
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.