Python Cookbook (2024)

Table of Contents
Problem Solution Discussion See Also

Credit: Luther Blissett

Solution

Here is the most convenient way towrite one big string to a file:

open('thefile.txt', 'w').write(all_the_text) # text to a text fileopen('abinfile', 'wb').write(all_the_data) # data to a binary file

However, it is better to bind thefile object to a variable so that you cancall close on it as soon asyou’re done. For example, for a text file:

file_object = open('thefile.txt', 'w')file_object.write(all_the_text)file_object.close( )

More often, the data you want to write is not in one big string butin a list (or other sequence) of strings. In this case, you shoulduse thewritelinesmethod (which, despite its name, is not limited to lines and worksjust as well with binary data as with text files):

file_object.writelines(list_of_text_strings)open('abinfile', 'wb').writelines(list_of_data_strings)

Calling writelines is much faster than eitherjoining the strings into one big string (e.g., with''.join) and then callingwrite, or calling writerepeatedly in a loop.

Discussion

To create a file object for writing, you must always pass a secondargument toopen—either'w' to write textual data, or'wb' to write binary data. The same considerationsillustrated in Recipe 4.2 also apply here,except that calling close explicitly is even moreadvisable when you’re writing to a file rather thanreading from it. Only by closing the file can you be reasonably surethat the data is actually on the disk and not in some temporarybuffer in memory.

Writing a file a little at a time is more common and less of aproblem than reading a file a little at a time. You can just callwrite and/or writelinesrepeatedly, as each string or sequence of strings to write becomesready. Each write operation appends data at the end of the file,after all the previously written data. When you’redone, call the close method on the file object. Ifyou have all the data available at once, a singlewritelines call is faster and simpler. However, ifthe data becomes available a little at a time, it’sat least as easy and fast to call write as itcomes as it would be to build up a temporary list of pieces (e.g.,with append) to be able to write it all at once inthe end with writelines. Reading and writing arequite different from each other, with respect to the performanceimplications of operating in bulk versus operating a little at atime.

See Also

Recipe 4.2; documentation for theopen built-in function and file objects in theLibrary Reference.

Get Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Python Cookbook (2024)
Top Articles
How to Maintain Your Work/Life Balance During Busy Season - OfficeTools
Why Buffalo Exchange And Crossroad Trading Grow Rapidly
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 5527

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.