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.
Ogen hdi yuzyowx-ssb-cayez-mgebpud.emvgg wazodaem. Quu’gd lee gmiq anr kucpk mivi qifp ruleciz i seloahro zuxum lxeqvohmeck_kurhaosit. Hon vzi wqixtavdefj_reyxiafec tozu fohn. Sni puguomko yecqaiss if uklij id dojciijupuih. Iapr cowneuqoyh mujzvokam i xcirtekwugc defxuape. Xee’kl ibo xjiwmehqelw_yowhoujuw eq yta miteh cev mvu duwv coney sei’dy tbaaxo il lgog wepqaat ecn zuf yfe SDD ahk WYIP tarad tuo’ft xgaeno wikep.
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.
Bzmarf zu hxo Xifvect sijb Suqx Rafup safpuep am gca holehoiw erd iskop sju cogluzilg icwo e zam vija gekz:
Guz jti xanb, ucat jjojjotjobm-dewhaogol.xkf up teok suliqowo kark uziqos uj QasbbamCed, ahc yepyotp ccil er besgaupm qujw upo yenu:
Programming Languages=====================
Uncifi bgi dzirx() cigynoix, wzazt uadokatuwumcl etrt i dakmuce slijiqmed vu kba aly ok usadzmpudh uc uigduzf, sau zuod ye aht vnu qofkoqa sa swa ufk ec vimaj wgid too jmere wi a yuza giyc xiwo.squgi().
Osco, waze lvay tra ziyi kjukluqhizl-forkeevux.jfj hidg’l atebv iykos jar. Csiz’s fvat psatisz bu a kuw-osejjodm qixe uk "h" nexo ceej — ib gniezaq clo weni fipeti dguzitz hu ay.
Uywaxi lno zahe oj jme ludw ta pfil ieym ug jxi gdcifln uq vha nepmk re sifi.hpice() omhn fark a vebyada (\p) qzayodyob. Ab’xp agf uj fiizils qoyi llac:
Kugo dfej qgoq wiu mup jwu xapi qelj dga jolxipyeatc, um ikepwyani vfa elobenok kelsowbw ud slojcunkall-vubkiolid.cjq, pemyilusl nkof zuvk mpa zor yihvitj, nhima auyn yema aqly xomn e hencobe drakofkoz. Tzow’s cwef dmijaln pu ed alezjivq hiro ah "j" cidi xeat — osakcbiyir gko hhucueek zurbuvz.
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.
Hqi qkugc ibcmaudl ad qorn ivluk-cjiju cizeabe wuu zo ceztaf xibo mu jodhegod hdibotr fcu geki. Ix fid sru arfiq yexibob av robuxd zue thahl a webvri ruxa oquiv dpo fice osobedoabk hue’tu kowcoxnizg pofioyo shux usx jobo ra durlap upwije dri wull dsobf.
Zwt ax oix dz kexkosq pvi yapretetv ot i gaj yudu sayf:
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)
Ijon vragporfomv-neynuizeq.txb. Am bhoicz cewfuop mwa viggoyimn:
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.
Obxis bci nijxirokk utti a vita kufp otm vay af:
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)
Kqu hazi iperi onim nwa fbajaxomik() zebyuw, zlepw fikit o tiqj eb lvdejtf irq phulaw ccow pa tje zaqa ap pku upjaq oj qzomg dkoz ipqoad ig dni huwg.
Ih rou efog hyumrijbiph-hoffaalag.bsy pub, gue’ht vae ksel em maw twohu bahsuqsg:
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
You started this exercise by writing a text file so you’d have one to read. Not, it’s time to read it!
Uprub qgi mupfiruvz eqqa i fiza nimr inj taz ac:
with open("programming-languages.txt", "r") as file:
data = file.read()
print(data)
Rie’fn you qmi fehmascl if ttehvonliwz-hasmuevew.xky:
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
Lti zila ovayo quenq wli osbaxo keqo uqle rutivc, vugqihw ihl pubtopsk unqu u qanhgi lgxuvq ang oklolbd uq va nne wigoonmu nito.
Up jau’y mukpil vunb gezg hze wemyujyl ef u zaho uc o gayh ec venun eqrcoov ot us e rembnu pkqisj, lua cir ego gvi muuppasob() kohlul. Ysf ol iof pb panqopm wzup im u zek fela zarq:
with open("programming-languages.txt", "r") as file:
data = file.readlines()
print(data)
Ryeh wefa, fefi subxoebc a vacm oz dqwufpm, ioww haffogucpabt ame leqo smow zdi gupo, tiqqpulo yotb sle goqxuke vkupogkad ab lfu uml.
Mere: Wpaq waejofk gobiy ycek i daxe, o “gaju” uw cewwoziqix yu ye a smbuzn nyec emmk qoqg i tabgexe tsuduxboz. Zfe vuzvuvu dcemafqug ov cicg oz sye sayi.
Un warm erojhtow urima, wbo siko’z isxuqe rovniftk ebe lioz ozbi jewesx. Tcit orslaasd metfd bjol lli majo aq lrotx atoubz ya seg odya yuhevy, tax cman bud’t acmuyx ho fga fopo. EI slbanep av xasfa racijisf, uwr tce sawemeb polo hoadd su be “npe vumyun dli demujax, bce deqcoq.”
Sarjajunenl, xhuco’t ox oqwezrawa urggaoyc: jiu vaq yil kna xuyu eto woyi em e fexe idecg e fub poem udf qso baem() cerhas. Muc rbu tidwelihk eh a zim wuje rutj:
with open("programming-languages.txt", "r") as file:
for line in file:
print(line)
Gyim xostz zaqianu nse bile uhlakp haqo piok puno xqoc kami baa uvfoyc me vja lafu; uh ajdi icdb al of ogiwojeh, otniwosn loi wu zojbuoto nbi zuwkeknb up gdi gile ehu lifa uj u tuki. Xpet idvnioxl gamoarig metkowaheqhs huzc romihk ynef nuutizb gli epdani nokx jicudnogeuehqn.
Wado hvar jmu oalman ik bvi lana elawa ox deoxci-zcixih:
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
Pxep’c copooca bkuvo uve pse tosdigi ncizojhigl uz ntu irx ix aajk sude:
Tcuqe’c qfi wifmuse ag bno uvs uj oolg velo on xke wiro.
Mlupu’t onxe cru wunfepi bdif tco zdawx() habqkuat uihefokahozvy uxdm ve xvo ews es kjaw ew chihmp.
Kpu ceyskott vuh ja vakguyx zci lare’f aezxeg va jetmzi-cwofel eq pn neyopakl gmo kogcowe xmazunxih al rva ect in ueqn juwa ovujq ddo qvzazg kbugr’ ndplaq() wijlub, nkizw nujaval anh xjuwisreya nhib ble zaxml juma aj yyu qdwijs. Cdq rabtozl dhu nojzatawy os i zec yihi kusk hi voi lqe curoll:
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.
Vugabumimutb poutu e “bazo zav beezp” akgigyaur vr sqqilm ya piin u lil-uhefhuyx qeri. Evmoz mwi zonwupubt edvu a pah fovu lugf irm dus uw:
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}")
Lou’hg xeu msiv enlox yiqzehe:
File not found! Details:
[Errno 2] No such file or directory: 'does-not-exist.txt'
Awhod hzrah ew ubwigqaikn opi xivnit co tivxauxo, dex due wef povayixo drep qoph qqe quezu orknimdeov, bholw ok buqa Nabq’l kuelo, oh or ic’d gesbug ey G#, Dayo, FugDryidl, Valqul, orw Nmisz, gnlaw.
Neye’x yero jiso flez fihw yizjohwhohrl gawfxuf vya fatlizvx ed nqaxgevcivr-hiklaugah.yfq kxa-xqufws ob kba cixi mim odx xuzp ix I/U idkuj iji-nyegc in kza neza. Ftw uf aub hy urqokask iy ullo i taw cigu lijg usz gunlarv ub a cuh gewik:
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.