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
Mortgage rates today, May 3, 2024: Rates increase for the 5th straight week
What Are Privacy Coins? | The Motley Fool
Worcester Weather Underground
Tmf Saul's Investing Discussions
Dew Acuity
How Many Cc's Is A 96 Cubic Inch Engine
Costco The Dalles Or
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
Wild Smile Stapleton
Craigslist Cars And Trucks Buffalo Ny
414-290-5379
2135 Royalton Road Columbia Station Oh 44028
Lax Arrivals Volaris
How Much Are Tb Tests At Cvs
Michael Shaara Books In Order - Books In Order
Wisconsin Women's Volleyball Team Leaked Pictures
Second Chance Maryland Lottery
24 Hour Drive Thru Car Wash Near Me
Adam4Adam Discount Codes
Vintage Stock Edmond Ok
Band Of Loyalty 5E
Evil Dead Rise - Everything You Need To Know
Google Doodle Baseball 76
Kamzz Llc
Blue Rain Lubbock
Qual o significado log out?
Craigslist Houses For Rent In Milan Tennessee
480-467-2273
New Stores Coming To Canton Ohio 2022
Lacey Costco Gas Price
Craigslist Boerne Tx
1964 Impala For Sale Craigslist
Calvin Coolidge: Life in Brief | Miller Center
Manuel Pihakis Obituary
Jambus - Definition, Beispiele, Merkmale, Wirkung
Jay Gould co*ck
Edward Walk In Clinic Plainfield Il
A Man Called Otto Showtimes Near Amc Muncie 12
Finland’s Satanic Warmaster’s Werwolf Discusses His Projects
Captain Billy's Whiz Bang, Vol 1, No. 11, August, 1920&#10;America's Magazine of Wit, Humor and Filosophy
Qlima© Petroleumofen Elektronischer Laserofen SRE 9046 TC mit 4,7 KW CO2 Wächter • EUR 425,95
Craigs List Hartford
How Much Is 10000 Nickels
814-747-6702
Tableaux, mobilier et objets d'art
Vintage Stock Edmond Ok
Yourcuteelena
Wgu Admissions Login
Understanding & Applying Carroll's Pyramid of Corporate Social Responsibility
Michaelangelo's Monkey Junction
How To Win The Race In Sneaky Sasquatch
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.