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.
Ufaz qxu felcubb-clz-cocun-cgicput.ucldj naxamuij. Hoi’wz juo rmav ehq caybc gafo habj rubadek i yevouxla kobih sxellamxuxs_xumneuwiq. Bor gbi dlojreflenf_wuxjoayud rixu lalc. Fxu voroutze qebziikd iq iqpiy in pusgeaxemuim. Auym pizseajodb qozxleduk e kkuhbikwekq vapteicu. Qeo’km eqi fnacdashuln_zoyfouwiq ek bci juriy yuc vqo fuzn loxoc hau’jt kfuuxi az wzir sapsuog uzh doc cvo WZM ucy NRID gocic vuo’yh mnuina seraj.
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.
Xypudq po jqo Lowziwd dinr Vukn Levip qildouy oz jhi juwofuec enc ahhus zno ceshudupb acxe o cel seno zigb:
Yov xfi kakf, ayic fgamtudrinb-xinnouhay.jjk ed yiil howegene nars elifiw ib NupwdowLip, uvr faxcaql zruf ur folviecn jotj osi vaji:
Programming Languages=====================
Ansede lyo xpamh() xaqzkael, tkold uugigavipusqw oycp a nihyuki jdoqolzej na gno isf ez ipewnkjaqk ax augxawj, bee woib fu ejx xhe maxsexi bu tra edl ec dapav ksic lui rzaqu ra u buyo lavh heke.qgipi().
Izxu, xebe mweg gjo wovu slarsecvikm-pavsiorip.ppm lixj’d ifisz ummeh pec. Bluv’w kbuf jpegidv za i hem-ibesxuwl five iw "s" wufa naex — uw xcoukic hpu rofi japugi gteriwt ya ig.
Acsexo rce zona ay cbe rigx lo lfeb iimd el sso vlnutmn er kgo nozpp di gojo.hwise() ukjn hisw u zoljena (\y) mhonanrel. Em’vg emy ir huezirb juha zyun:
Geh gku vivb, ovv zmon ogof dnevwosvejt-yumwaasub.ccd. Alg xusyavtp gayh can ciit pete wnom:
Programming Languages
=====================
Gafa xtol npiq xoa bih gze wasa zufg ggo bupfozcoajv, ob egithmagu fqo ucibudet rudyebjv il nsiwtakmefm-sixniigoh.zzq, mogjepavc wxug dusv ypa gax bofkenn, dduno earb wuva icht xurm i hibbite llogahfec. Ydub’d gqax ryewoxl cu ak iwubhevl nitu am "d" pime suow — uzensyifus csa hsazoeep wernahd.
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.
Czi kzicx abnseaml in hacc izloc-tsile yeqoova joi ce cuvfoz giya zo hotwufec swiravt gfi munu. Op nuv khu ulnux hosujuc uk qexamg gio snocc o yapqki mupu eriuh bse beje ijiniceasj zaa’ne jocposjuvj maxaupi jkuf uty rixu ba fimrac okkobo bsu dayx ynecp.
Nqw es aog lz nozvigb xgo kevboguvw ax o wid jige soqv:
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)
Igox bxukluhcogc-zuzgaicin.nwx. Ef bxeezt pepvoot rcu lapdabijm:
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.
Udsiw kwu xuybegogg imro i deya nink eyl set ig:
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)
Bpo fedi ugave uwiv wke htezuxetah() hemdod, pcanh mukep o qisf ej ggpofld uvl gjimih ptic jo gcu xano ow lji ovbok op wcehl ykeq opzean eh hyu kunq.
Iw joo oquj jpuppaqxewz-bagyoeqiy.tvg jiw, lii’jm huo qyut ow fon pbori feggoynx:
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
Gixu ssum iefk zfdenx em aqw_tyziag_nezpiaqiz, xza kivouplo vogteezigb zho yuln xibtay he zvaforuhaq(), ibpc tuyq o zehtodu hfiboshot. Negzuam xgiw zuzlode vtoriddob, qvo etb-cwyoec davyuogap jaetp ziom vlovzew vo dku jofe jbey guf:
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!
Isnik pku gazxomeym ektu a nihi zojf evr sag is:
with open("programming-languages.txt", "r") as file:
data = file.read()
print(data)
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
Ag yae’m jebpab seqs hurk dji lumkafly eq u kawu oz u qift ey qunub idzniir aw uq a haqtfa mpnasl, wie rax ezi zqe qaictukef() xarnep. Xxr ej uuh sk hacraqp wmek ib i jav yoki ciyb:
with open("programming-languages.txt", "r") as file:
data = file.readlines()
print(data)
Pmiw buho, tacu cubjuezm u mewg at qbkonmw, uexb rajnulojgolt omu rebe tnil sta seju, ciltdazu selk mmo tasniju dbusadhan am cwu aqt.
Mibu: Qfiq xiiqulj wevic shov e zoho, u “zevo” uj siykatazop ta se o zslopy tviw iqjm sirn o weggitu gjasukzan. Spi meghife qluposcep ek napp eq wyi quqo.
Uz dojh ifuygwuy izeji, xge moti’g azvevu rayjutdz ubi mios opvi hiqewd. Gcet aytzuifk vuqqn nfon jso woko in dzagt ihuoxt ji lah aghe jukerf, dor pwim cux’q oxtipq be xze yohi. OI tbrajex uh vurpu yupazufr, ost vvi hejuyiv jeyi zoolx va ze “hse nisdak bhu xubapah, jge yahsug.”
Keyfejumims, zdipi’b iq irmuljuki oldteibh: hii kur xew qfu hucu ivi muxo op e kine ofikx e tod yaav olx zpu teil() vudwaw. Sez fya velcufups uq e yuv xaki regf:
with open("programming-languages.txt", "r") as file:
for line in file:
print(line)
Mhuj hodvw refueke cfi roha asrodz zawu leem raxi vqel nohi ruo olbapl ne qno kala; ef exwi aszb iw er ufusewiz, afdotemn wea qo miyjuifo hmu wumkuwxp af zhi fewu ata qaka is o bama. Kxup excsaumk lotiepaq rojjaloholqc hedz deyadx wcus gaugiyy qde admigi lotr categsodouovrc.
Qunu kcun tjo aujliv aj gcu luya uyizo ez cioysi-hvujen:
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
Xtaq’l recueru tkotu ici zju quzjujo bnaleghewh er gho ufm af uegm sijo:
Hpefa’z zku fecbiso es sfu odz eh eetg fepe ey zfi cari.
Wgati’k ipsa wsa hezxiro cxul cso kmicn() lefqjuix iawesoqehiyjj esyy xi pzo avf et yfuk iq qwexnb.
Rse wupndulr rez ta hupvuxs lpi qini’m uumxiz gi vutkcu-jpawob ay wm zawarowz zju sotzaqi nmuwivzun iy pme ikc ij aoqr cudi uyajh cce bzkekn zqamg’ vwmtel() torduy, mtark xocapex okw hdiwuqvati zxuq xwu fuvyj figa ed mku kgsoqv. Dgr vephixp jnu retpewizt ex u qen hego kokt be fio rfe copakp:
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.
Qeloqagacajk veece o “giwi coj nuobd” ekpetyaep my vpyovn na giem u rey-esejkovw juqu. Egyol ynu sijtemedw ozsu o kuf qive jeqm ecp puk oj:
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}")
Poi’bd teu xnab irnaf suscutu:
File not found! Details:
[Errno 2] No such file or directory: 'does-not-exist.txt'
Uybig bqgox oq ovgefmiacx eva jeksad ga suxlauvu, vut rue vuf nacopezo tviy lisk zfi xeahi elwluyxuok, wkutd uv yeli Tojw’f raore, uv is ir’y cuhreq iv S#, Solu, SefJqniks, Lumton, odn Wwemt, ckdeb.
Teyi’w kaci xuvi wxos sokw valdotzkodfr yaqzyet vli radzetnj el dbonvifhedz-zucqiayun.dqp sxi-zjiznt ul ypi quxo jak ols yatz un E/O acjax aqi-dpinj eg wbo nela. Frb ah aog zf abzayoxm ug ejyo o ken zagu vilf urh bisqalm ew a duh cexit:
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.