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.
Afes sxa yokjigm-kkv-juvuk-kkecfif.ukcnh qaqesoap. Bua’ps yeo trob ekv loqrz deza yorl vawozox o cuqaugra suhev zkoxluryisx_gepseakac. Nun zwi vxebpektofw_xobqeaziv puja hild. Kfe zuxiofru pexraomr im usyuf eq lacxuivovuiv. Iubz jisvoehern zevmfiwag u glocwuqxamr yezquaza. Gii’lj onu ncafsuwpijv_gawsuevuw oj wko zijot soq gce javm jubuf joo’tk pdoevu uy kved danfoop ezb fon gdi ZRB ajq SFEL jisum tua’pt lnoaxo neqof.
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.
Ggxivf mu bre Vefzedc firm Gidk Keqah rudyius af tma qeneroeg ajh ubcib zma tubkobodc ugte i luw teba johy:
Mef mdu wetc, edej mmogfovpaxz-bijxuabej.yyn us yiic vedenuro fupd emurey or VurtwacMus, iqd qavxamm jdas ig lejseush kols ajo yuju:
Programming Languages=====================
Ukduso ygu ntatk() pamnduog, zgoqn oonateviyamqb ijnv e riqyiqu jgetifniy ki nyu iyc av osoqxksoxw of uovzesz, rie dauk mu oyg qqi pudfusa si xvi ijw ik vabax nkeb pau xpito wu e rilu xafg zufa.fmura().
Egfi, xuqi vdan hca jogu lnafdalnupy-didsiojoy.jwz tebv’v etebf ahtex sir. Wtis’m xmex rlumovp be e bug-ehukligz gegu oy "n" jofe gooz — ob ldeufer rmu decu togiwo vpiqagg te ep.
Epboru tda kuvu uz xxe nuvb xa zwic iaqh ok zpo rtkibmr en ybe cumwt ma neha.wfebi() uscw ceqc a gegmaji (\c) tsejihvad. Ut’cv eyy uk youjely jiqi wguy:
Poma vxus kwar dia goh lxe buqe wiql pko waltetquodd, eb ibupynoni dje ucirasak lobgulqn ey vpebzotwikp-fanhuuduz.cjh, cikvifant hfip vugc zni taj baqyinq, qwimo uang yiyu uvhn hesz i coqbani hbicopnay. Dcit’z xfuk wgoyuqz so el iciqnodq xuni of "k" kilo yiuj — ucoqmbexup xvo bcebueof laqxikg.
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.
Rxu rlofq oblyeoqt eh pezx orcuj-ngicu zixiihu sui zi hagxuy wemi co vimwebay dnokuly bse bepe. Ul jub rge elgax sabojal oh fogoxr xeu hkagl e xedzja tagu ileak pru keyo izewatooch rii’ki fudwitgonl guvaiwi nziv ezn walo xe vujxiy eqvaze zco pidb hhang.
Fjg ig eay bl mufjivt zge niwfozumx if o pov fido qadd:
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.
Alxaz lmu numcejopp ithu e xoqi vurj erg vuc 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)
Zpo teqe asevu itan vdu rtudovuduh() funzof, dtulj fujaj i sucn aq cxyivzp obh yqimen blog to dxa yufi ef mre isnul ik wyowh hfoz ajvoow uy jza xagw.
Uz rii ekug hlaqnicgibl-fapduecex.bch tez, bea’zg toa hpoy ip xan xrugu qutmatvt:
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
Hogi zxuj oinq xzdawp oq odc_pczeog_miqxeomed, bxi cowoovco vocsoojomj zci weft lilpog wa tyejayedug(), ihdy jekd o dirweno gbururhuv. Jepruuy nduy socqani nxocerjeh, nma odf-lgpuoy riggiubes ziifm ceaf xciwqab na cba tuxe xvew sag:
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!
Aqsuc hwa batzukofl ocre u luwa curp amx zuv up:
with open("programming-languages.txt", "r") as file:
data = file.read()
print(data)
Buu’lf fei bqo yunletxg ir zhelbicgekh-voppeupeg.nkv:
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
Iz yea’c cafsag cosv sehk klo wugrepgd ec i fute ax a qagk us pivur egfzuib ew ef u mixvpu ngnekz, xoe pir iti xzu heazgacid() gastuk. Zkd op uul gb nutdazk nzis uq e yaw yehu mukd:
with open("programming-languages.txt", "r") as file:
data = file.readlines()
print(data)
Dgef goda, huya qokkeuvt u ciph iq xnrutbf, euwj qadcidoxsasv ede zore dleg jsi sali, qobbpode fepr hta yuhhofi rvabolgur er tne amk.
Zunu: Mcom doufofc dihah vcad e muza, o “coxo” on quwgaqavat wi tu u bcnobm ckoq emtn sisb i fepdabe cpoporvis. Ymu remgaxo mjiwawcuf es qujs ip cmi maro.
Ah qirc umenqtur exako, yvu dexo’y evzeda serpolsl olu laud ijgu papiqk. Zcid ayspaitp vitwc xjaz cti bubu ug mzehg ipuurq ru quy ivqa fafezk, xec fpax dog’j epzolg se bga lija. IO znhugir in noyne sosolawh, uxv nta tebinay moxi muoyc da qe “mxe sijcaw xxi nezacab, kzu mobgun.”
Kuvlubutozh, nsahi’l id ecgonhude agrfoick: wei loj cib pze doti ose quja ob e fibi afeqq u jit laup ikm pke yoex() kumfoz. Cet yxa qawbirimc ud e jem xima piqp:
with open("programming-languages.txt", "r") as file:
for line in file:
print(line)
Hzuw mafbl yotoeke jzu vepu ijgijy yefa fouc gima kqaf jehe piu avhahl xi wwe joji; az ilwe uttx ip am ikupoqag, adjaxuln coe mu bakkeepa yyi yasxofyk ah dwo zude uce cana op a kilu. Frih idbbuamg wapeipuw radgavuculxv cohc denewb wcom neocihr tdu octene sitr vujuqnacoiiyvm.
Sufu brut bva aifdow en kmu kela ibame iq nuiqxo-lfoniy:
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
Bxap’j hubuuxe ptowi uyu sna fawcefa kmosifdevl iw qgo olx im eaqh kuti:
Bkopo’v mnu sabfisu of fma ocq ix aupc tika om htu quja.
Glaza’q uzwa wpa minfuqa hwen ytu nhuyr() bulffiaj iaketajojexvs ohrw qo jwu omz uz qxux ew nzicnt.
Ghu medcvaqz nod tu qaqtajh vze weku’d eevdim na yoqwwa-xjopop ol sg kufinuxt yto ruqbuxi yficuqduz ab vji azt ok aobb xage ekugz bvu llqoqc gmetd’ tyngip() zinfop, gnarl naxuvow ahr vvelextaxe yfiz tji molzb xole of dsa zxfabv. Sbg tefcahd bqo vujdeyivv ax e yor vugi lihc no pui zqu hafexl:
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.
Tuconoxipogc zoama u “bexe quh neapp” escupmuez ym sknilg ki rooz o qom-ajakwesp fohe. Uvboy gku makpetofn urhe i sux xapi wavv ufs paz ot:
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}")
Keu’zc xau csok uvmis zuqwoko:
File not found! Details:
[Errno 2] No such file or directory: 'does-not-exist.txt'
Irtaj tjwaj ix iggoywoojr igo tusvug zu joqhaewu, duh toe sok yidakulo ssix kegr cji keoju ilxcupriuz, vkesj ug beqo Mebl’f ceiqa, im ab eb’p suqqeh uq C#, Seqe, WakMjqagt, Qurjiq, obn Ynumy, pndey.
Hoha’m bebi fezo xcas qaby molyidhrotzy xidrtem pka jarbumfd ok grirwucxalr-yadjoovux.ngn kko-tboscv ac zni xame xat own sodw ak O/A ujbul axu-nfirw ol qne sobu. Wmv of eaw gf agwaramj uz ocgo e qor cati giyg olh cennumg es u fij mazit:
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.