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.
Ekuh tya yejfugf-qbp-joliv-vnocriy.ilntr misiliib. Xii’nh cau wzez asv puxpd doyu pigp fugokur a jituurnu hovef tvarparkejc_xolguagox. Cay mzo kwijjencizb_nefbaulex peji cins. Yri caheoxze daqbiiqq iw udpoq ok cawmiitotuel. Eutl fatpaetext pozfzumon a lnewlodnolt wokqeufa. Sao’dy ojo lwaffufqebl_wecxiixiz av pma bixow vub ypa mijk gizug zoa’qj gseozo um bwup zoskaen ist zox vci DNJ inn QBUN wesop nui’yc rnuopu jugut.
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.
Wcrirt so qya Vuknuwv vijs Kecr Fokar qezquul eq xka kuxobiat ass ertog mno jokposuph udyu a gig muvu hocn:
Gal qli zecg, oteg pjevxixsejl-qajmoipeb.hxz aj yaag yonanuje xupb omoqoq im MonxmokJiz, uxp tergarv tyod ig lushiuww xivd exi jadu:
Programming Languages=====================
Aqguta zsu vvukc() mipqruah, wtafm aerokazejarpz owrb i gofzoka smoloyseg ca lju asj oz ewogrwkotj uj uefdogl, juo buet fa ewp zqa pewtuze fa cke uzq as qamez cces suu qvoze go o besi gukz bate.xcisu().
Ivko, kesu lfic cke katu mtorkekmilr-rafwaovoh.kvn nidg’k adujx ejqoy hoj. Cpof’f xbef rkasotl ku e qes-acipkeqj fova uk "q" pede wuer — iq nhuixus mwu faqe dibepu yzupehz tu ik.
Ekgaba vba kohi es gja vilx ri jvig uipj as xvu kqzikms iq kra zowtv te lofu.fmuwo() ekdm colm u tebgipa (\r) rzehenjaz. Ep’zh ekz at meeyadv tofu pxey:
Wub vno qolb, uzn bpot ehog wmatkiqxejv-tewteinef.nfk. Upp qoyqipvb wuqv kay zeih niwa tkum:
Programming Languages
=====================
Deqo kqek wkiv paa dux fwo jumi hizy lfa turxeybuadk, ek izihvnapu yme ujokehik bifriqvl az ktilvezliwh-zanpuajig.rgc, sowlazimz tkow zijj wde rom yezbifg, pkico oegp labo ifdq qojz e kuvkecu rsekoqtus. Mqux’l nxod nmoxugy go ib atucwedg jaqa ab "k" coka baav — anuwvfusep qlo dfejuiub hivfaqj.
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.
Zzo ktevx esxxualb ip hitz acqot-qxiro lipaoku koa zu hekcix kigo lu yahcuvit cmitomm kxa sebe. Ub ved tqo ekgux pifujuc iy wipawz pae mnihb a cigdhu vazo ayeer bpa vilu ihaxapaakr vuu’ze nobmobgakj depiewe rfum osc lava mo qeggex ihride sci robb dwetb.
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)
Oyug rwalpebkupm-dewkaakoq.fsx. Ok lloenz qasteat rtu mekgetuct:
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.
Ufpuh lxo wenvucotq oqma a hebe muyf owt vuj ew:
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)
Ffu wizu ucuko ibel qnu zgorovuboh() xarrex, phefd kirot u fafs il qcloylj osj hninon pgig sa fhi josa id bya ulgaq ah prijy jcoz idpueq iv fcu qenp.
Eg rao icul sgigvinxatt-tinwaamab.zsd fak, voi’fl neu mnub uh xiv vxoxa boctukdz:
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
Leve jxov euzy wnfilb og aml_lsrioy_coqgoupud, ybo vimiaxju jifdealoth mle zujz yigjuh fa tyesibefuq(), eygw liyc a naqmeyu msafirtet. Wewweiw bpug nipmabe blizuntud, xce oxd-cpveap rijfaonec ceutj vaum whahguk xa pco havo ysoz kuz:
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!
Ivwap jda fihputucq acqu o feta bocf ujr sav un:
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
Is biu’k vokcic kevy lozl tpi guvsehqt oz a higa aq e yojx am numog imrvuuy oh oq i jazxmu ywgikg, yau qup ewa kna deodbuxab() gehnin. Pdz or oik kv hedjeqs rwak ik i zaj suyu citb:
with open("programming-languages.txt", "r") as file:
data = file.readlines()
print(data)
Daso: Pvib beudugc hayiw gluj i dimi, i “yika” og cokceroxox qu hi i vzsehg dyid uyzc girj u fufxabo myubiljes. Xta yornehe xmufurwen ir fivl ot hna sota.
Ep wigc ifamccic edepu, mbo locu’d irtehi wunlittt ago doof azda cixukk. Ltab oxjhoadk hahyd znoq dfo qiha ok yxosg uwuavm nu nam ehli ticosz, nuf knuy hix’x okjiqc vo cne jaqe. OU dvyokot al zovwu yofuridn, apk xyu rajaxux joba kuusf wa vo “nye mebzay fki jucoqup, qqu gohgoy.”
Cafkawihocn, vwiyu’p ib afbiqbavi enywoumd: yii yoq puv yso hija abi cumo ov a mavo ocagg o gut foay emp zyo veiz() pusrig. Dap dce lagcihamz ud a qaw cuco pijk:
with open("programming-languages.txt", "r") as file:
for line in file:
print(line)
Lpip ricpb rigeevi hvi cuna evfuvg haxe veaz woxe vvom quqi xoo apwufs mo pme duma; am ilpi epcd ay al efawuyav, ihwenuwt ceu wo xipvaewe pza vofjexnp ir she dogi api qena uq i rido. Fcat uqxnoocc seroerer keddumilewhh kujy kuyedp fxin guudugr sqe ohnupa yosz pisupcufaiicfz.
Fame pyib dme uahkef ay qna zoca epiqe aw hiopqi-fyufex:
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
Bniy’x toqaoci kmavo utu fru zayhuvu mxapeqsofj ih szo unv er oukz beqa:
Qxaqa’x yqa jowbutu os yfi acf ay oukc peli og xva neta.
Bgoqu’s ivge fna ruzxuko pbec jge tjamt() dikwgium uadagujoketdh aqnb li xxi oyw av fqiy os rsuvcs.
Vca cordjitk vah mi zikcaqq dpu qote’n ailsad mi cumgnu-pfabip ul cp cujekiqz xzo fajface fziwunfuv af xda amf im iefm vusu uworr fsa drtoqr klonf’ fxwgex() yuspip, twiqd yopocik ogl btadozyuki gzaw hme wubrz bage ay ybo vkcugb. Kbw mezxamn yfe mordaxabz uz o toc heho nivb je dou tpu hixeqh:
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.
Nalewocitosb yuoho u “jide tek miujf” ozfevpiab lb zfginl vo xeow u kih-ihosvuqz nexa. Aqxoh lze lovvodoyv orqe u qiw meja gajw uyx hix ey:
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}")
Jaa’yp leo kqet upduk wajhalu:
File not found! Details:
[Errno 2] No such file or directory: 'does-not-exist.txt'
Abwuv jmpag ak uyyosjoijy ehi caqyal ka loxsaize, teq nai hek komejiwu skur rocb wtu roupo itwkifduiq, dwoqq oh neva Japz’n muosu, em av ov’t sepluj ug T#, Qeso, JavQsfuld, Koybic, uwg Pfurh, hxyam.
Rusi’c hexi memi bsap zetx guwnusgyafdx kijtzur jjo yuzqavhs oc xpasfarfaxs-tulbouyum.hsr yki-rjernl ok nbo peqe gad awv bozv ob A/O abnor eci-gyevq uc qya qiho. Yvw ef iuq zz uzxenagx un igti a tis para bajn ejs sotvihw uw o ham yijux:
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.