12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 14Files14.1 PersistenceMost of the programs we have seen so far are transient in the sense that they run for a short timeandproduce someoutput, butwhen theyend, theirdatadisappears. Ifyouruntheprogram again, itstartswithaclean slate.Other programs are persistent: they run for a long time (or all the time); they keep at least some oftheir data in permanent storage (a hard drive, for example); and if they shut down and restart, theypick up where they leftoff.Examplesofpersistentprogramsareoperatingsystems,whichrunprettymuchwheneveracomputerison, and web servers,which run allthe time, waitingforrequests tocome inon thenetwork.Oneofthesimplestwaysforprogramstomaintaintheirdataisbyreadingandwritingtextfiles. Wehavealreadyseenprogramsthatreadtextfiles;inthischapterwewillseeprogramsthatwritethem.Analternativeistostorethestateoftheprograminadatabase. InthischapterIwillpresentasimpledatabase and amodule,pickle,that makes iteasytostoreprogram data.14.2 Readingand writingAtextfileisasequenceofcharactersstoredonapermanentmediumlikeaharddrive,flashmemory,or CD-ROM. Wesaw how toopen and read afileinSection 9.1.To writeafile, you have toopen itwithmode'w' as asecond parameter:>>> fout = open('output.txt', 'w')>>> print foutIf the file already exists, opening it in write mode clears out the old data and starts fresh, so becareful! Ifthefiledoesn’t exist, anew one iscreated.Thewritemethod puts data intothe file.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!