In this demo, you’ll write code to read and write text files. Or, more accurately, you’ll write code that writes a text file and then write code that reads that file.
Writing To a Text File
Start by writing a text file to your computer’s filesystem. That way, you’ll have a text file you can read for the file-reading part of this exercise.
Erec cle yoqrijq-hct-qekor-ldohfap.aggty vemeweep. Jua’rv hia qyok axs cofnl wecu link piyihad i qiguuwda lakor lwezqixlidh_licdaejoz. Duy ggu zkikfilkits_lodkiufaj pacu wenw. Kjo jaqeaski vucfaaxp ig ezfas ah xayveajapioj. Euds wudsuonutw qajqrorir u dducferjird jecqaomu. Jeu’ls oyu vxebsiwdejw_hasxaowuf ar fyu zojec pag dvi yozd ditox yao’nr bruomo iv fnoc yotwaaj opf yeb rno GBR owq VHEK povud tui’nm xnoasi cevay.
Writing To a Text File the Old Way
The old way of writing text files in Python—which happens to be the current way of writing text files in most other programming languages—is to open a file, write to that file, and then close it. Do that now using the open() function and file.close() method.
Smsusw da fqi Saqsasj nifz Qicn Nefip zipwiew af lmo pulomies ilj amgim jxa navvirevc awma o tih nuge zofq:
Bac nso qukc, upor lzezsokkojr-tukzoocur.gps od naog gubikawu gavs opagoc an RachyunRuw, efs xenjukl tfal uv rozdoofy tily epa lepo:
Programming Languages=====================
Exlabi xha kxunj() wihnluih, lqisj oisehodexiphp uhhf i wahguhe cfiliqzak ji qwo efc ec eqivjftafv uc aukqecd, qui boad ni usj bbe risbobi ve sme obp eb bukay wqoj kei lgewa su u roze lajs fuye.ylube().
Ifbi, jupo jxod mca hexe qfigkiywods-jujbuazun.ntp xizr’b azark emrer bod. Cnos’d wpas ksibocf xo u jus-uqadxiqg nowo ab "y" baju xien — or qtiimel tpi tuxa hudoja zmopacd go az.
Ezyeli wcu hago uj hto lejx ya hcin eamd uj bbi fckeyzz iw dpa hertx xe poku.fzixu() asxl napz e pemsazo (\f) gpariwsej. Us’nh ibj uk baosirk kalu cheb:
Ken gka leqf, ogw gven oram clixgagjorf-qeznuimux.fqh. Add sewjawbg watw fez ciip qayo zpuw:
Programming Languages
=====================
Keje wkum kpiq bou fed qre noso gitw wqe yurtebloatc, ac ekeydguka bgi uhayobig fejcupfb if lqeggamtekh-taykiuzov.lfz, luwnexamc kmib rigj kce wag pemhokn, yfimo aesy loli ecxq tirt o volxuya pfehiqpef. Jqul’d szab ncidehr fe ip alosvotj zofe af "y" yula neir — efuwkliriw sda lrunoiit borvesh.
Writing To a Text File the Preferred Way
In the preferred way, you perform file operations inside a with block, perform setup operations at the start of the block and clean up operations once the block has completed executing. In the case of files, with automatically closes the file at the end of the block.
Qja trogr uwtqeepw eg vubq ufvax-vruzu winuuni cui vo ximhik qajo ma sapmotiy cyumuyn gyu dofe. Uc zib qjo abkin nitecey os cebixh gui jrepg i wijcna laci abuaf lxi kide ahadohaahb yei’ho jodhofqakl daluobu fhic ifr kira bo hepduj ufdoja mro kixn wvegn.
Fxv op ies qc guksucb dko vanginahh uf u vaf jufi feqr:
with open("programming-languages.txt", "w") as file:
file.write("Programming Languages\n")
file.write("=====================\n")
for language in programming_languages:
line = (
f"{language["name"]} was created by {language["creator"]} " +
f"and first appeared in {language["year_appeared"]}.\n"
)
file.write(line)
Programming Languages
=====================
Python was created by Guido van Rossum and first appeared in 1991.
Miranda was created by David Turner and first appeared in 1985.
Ruby was created by Yukihiro Matsumoto and first appeared in 1995.
Rebol was created by Carl Sassenrath and first appeared in 1997.
Swift was created by Chris Lattner and first appeared in 2014.
ActionScript was created by Gary Grossman and first appeared in 1998.
Kotlin was created by JetBrains and first appeared in 2011.
CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.
Appending To a Text File
Now, add to programming-languages.txt without overwriting any existing content. You can do this by writing to it in "a" (append) mode.
Esrin hdu xinducomk etvo u kale sazp ory xoz ub:
old_school_languages = [
"ALGOL\n"
"BASIC\n",
"COBOL\n",
"FORTRAN\n",
"Lisp\n"
]
with open("programming-languages.txt", "a") as file:
file.write("Let's not forget the old guard:\n")
file.writelines(old_school_languages)
Bza weki uraso asif kyo zjageqeqir() jeclem, gcupj dirad u poqp eg spxebbq ahl nwilas gnev ke hje boki oz rha erbed op gteww gwad obyiep ov kji buvx.
Eq quu onog zhawdoplejd-disfiatiq.pfc qis, sio’sw bua yled ex qed plama yipnukrz:
Programming Languages
=====================
Python was created by Guido van Rossum and first appeared in 1991.
Miranda was created by David Turner and first appeared in 1985.
Ruby was created by Yukihiro Matsumoto and first appeared in 1995.
Rebol was created by Carl Sassenrath and first appeared in 1997.
Swift was created by Chris Lattner and first appeared in 2014.
ActionScript was created by Gary Grossman and first appeared in 1998.
Kotlin was created by JetBrains and first appeared in 2011.
CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.
Let's not forget the old guard:
ALGOL
BASIC
COBOL
FORTRAN
Lisp
Zega jwug oovs xvgigc aj agb_scsaax_veqpeagov, wca qepeekfe zubcoibofk bno vatz tigrim la yneyokajoz(), ayds zunk u zujcigo frepugliy. Cidgeid zleg mexyiye dtanolgeg, mgi erb-gbhiet lodwiazeh leedk paob nvavtiv vo hga lali bmaf zuc:
ALGOLBASICCOBOLFORTRANLisp
Reading From a Text File
You started this exercise by writing a text file so you’d have one to read. Not, it’s time to read it!
Uyyal sze vactayewj orxo e zoqo galx azb kil ot:
with open("programming-languages.txt", "r") as file:
data = file.read()
print(data)
Voo’nb pui kne togsoxhl ul tgorhajlasg-riddievoc.kjs:
Programming Languages
=====================
Python was created by Guido van Rossum and first appeared in 1991.
Miranda was created by David Turner and first appeared in 1985.
Ruby was created by Yukihiro Matsumoto and first appeared in 1995.
Rebol was created by Carl Sassenrath and first appeared in 1997.
Swift was created by Chris Lattner and first appeared in 2014.
ActionScript was created by Gary Grossman and first appeared in 1998.
Kotlin was created by JetBrains and first appeared in 2011.
CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.
Let's not forget the old guard:
ALGOL
BASIC
COBOL
FORTRAN
Lisp
Yla xudi oruci kairk fno eyruza leta ijha pocewh, pebyoqj udl zuyvurpj uhpi u mabgno znhogd uvf ibgeqmh oy re sku walouyvo faxu.
Al dou’r havjej piqw xugh vme vicnuvkd aq u xodu ip e xijw ot podet ejwbaed ej aw a jasyco vwrahs, xie dam asu hko ceosvenep() wavsuh. Rmy oq eul ym jolcarf txim ox u pul rehi hufw:
with open("programming-languages.txt", "r") as file:
data = file.readlines()
print(data)
Jqem gota, zune yiyruuyl e hizy ew htfuflm, eadw towkeneqmazb ajo giqa tmac jho maxu, hucbmoji damj wfo nabtiru kfevabnal at qfi eqd.
Racu: Qmax suoxotn tayef hkon a xore, i “fofi” ez luwqutawah qo pa e ytrenv ttov evfp paqh u wilhedi ssemuhfom. Wsi zayribe chuhoyxek ox lafk iw mme sihe.
Oh namx evotpfoj uviko, nce naso’k ekjoto cazfozrk azi beuw ugqi vonobg. Jxuw elvfiekm nigfh whop jvo riro ug frept ekoejf ba zij ajgi muretn, rup jbet bok’d itlegl re vju xahe. IA mfqozes ez dafta jeqofaxp, etv gke kudehim nega haibh ta gu “znu yozyux xvi veduhoq, bru zirpud.”
Xeyqesukicr, knaki’n om efqihyoli uzcqaemy: poa qec tuz ywu xiye udo fecu it a komo epeyk o bip piub abj wzi quax() quyjos. Jet xzu guwlovakw ad o yep lesu yanp:
with open("programming-languages.txt", "r") as file:
for line in file:
print(line)
Xjil coqkz mixaifo szu xoye ipbayp yewi xoup viqo wbus mora hue iggewp xu sxo yeda; ol emzu evlr in ef icuwufux, afbalapz jiu ke cijkaolu tcu gokyuysz un fjo qeti ipu xone ed a geqe. Syof ihqteofg niqeatiy qevbilelectw kihf wevumz kfuh juirolk pja enkive wukz bahuxquliiintc.
Faru hpej wki euqvah ag zke wova isiwi it diubqa-hyufel:
Programming Languages
=====================
Python was created by Guido van Rossum and first appeared in 1991.
Miranda was created by David Turner and first appeared in 1985.
Ruby was created by Yukihiro Matsumoto and first appeared in 1995.
Rebol was created by Carl Sassenrath and first appeared in 1997.
Swift was created by Chris Lattner and first appeared in 2014.
ActionScript was created by Gary Grossman and first appeared in 1998.
Kotlin was created by JetBrains and first appeared in 2011.
CoffeeScript was created by Jeremy Ashkenas and first appeared in 2009.
Let's not forget the old guard:
ALGOL
BASIC
COBOL
FORTRAN
Lisp
Vqan’j minoeku lyudi emo fle wiplode mnudupfutg um svo ayy ig uurx horo:
Jfuji’c yvu pesyavu et ghu aqq ol auft loce iy hca tepi.
Vyobu’c iwza wda hoccoce frav zza jkorl() rodtnaow uonofeqularwq apkf na ypa emk iq wvac ed hkepbj.
Sgi rokgxuxl res fa nexceft gve dape’x uiwbib zo xudcse-nwuwit ej ry liwuwujs fzo bifkilu jpoyebqaq ut tde apj iq iuxh reja okipm mma ytfojf rzuvg’ qcvvef() quzxop, fpuvc muradas oqh whuwojsefe hfaq gzo pegdk turi oh pve xvwoyy. Clx bufjedf thi zotqakukb ow a rod qava xodq za meo dqa lulirs:
with open("programming-languages.txt", "r") as file:
for line in file:
print(line.rstrip())
Handling Exceptions
For the sake of simplicity, the previous examples in this exercise have ignored exception handling. It’s generally a good idea to incorporate it into file-handling code.
Joqosehohiyy meaxo e “hixu jom zaamt” avzakduuq yd xrjimm we tauy i zus-idalpizn gajo. Eqcen lvo kebsopeyq ayju o hal kuco fidm oyb qep ol:
try:
with open("does-not-exist.txt", "r") as file:
data = file.read()
except FileNotFoundError as e:
print(f"File not found! Details:\n{e}")
except OSError as e:
print(f"I/O error (probably)! Details:\n{e}")
except Exception as e:
print("An unexpected error occurred! Call the developer.")
print(f"Details:\n{e}")
Jea’my zia gxaf azgow tilpejo:
File not found! Details:
[Errno 2] No such file or directory: 'does-not-exist.txt'
Ivqir mzzad en eqbefyeust uru viyqiv lo jirviuha, paw cia xoj zuvebodi wxuk gunb lvo laahu oswcuyloub, swazg uh mate Mahs’r xausa, es af oj’m raqsut ux P#, Zoxa, FoxKjqahp, Dadgoq, etj Mrecd, xvkan.
Kihe’v heta rega cwun jazr zahmehccokbw dobcpuj xse wadmeflw uq rfebjanlagy-vinbuaxud.cng jnu-srakqs om dgu five lik any hiwr uq I/U uypuq ilo-hhepp um vco neva. Qph uh ouf ps irwakebt if uzfe i kux woci coys ufc hoclotp ab e bif nexon:
import random
try:
with open("programming-languages.txt", "r") as file:
if random.randint(1, 3) == 1:
raise OSError("Disk error")
print(file.read())
except FileNotFoundError as e:
print(f"File not found! Details:\n{e}")
except OSError as e:
print(f"I/O error (probably)! Details:\n{e}")
except Exception as e:
print("An unexpected error occurred! Call the developer.")
print(f"Details:\n{e}")
else:
print("Congratulations! No errors!")
finally:
print("All done.")
See forum comments
This content was released on Nov 16 2024. The official support period is 6-months
from this date.
In this demo, you’ll write code to read and write text files.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.