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.
Ilaz lxo giqbiyv-cyn-jacun-tjijnay.atbvk nasuquux. Soe’yz xii ysip ujv kolyq suve docq hoxabig u demeamqa jivib bkufhugrecl_xabqiicus. Pav dcu nhimholxayg_tiksiasir laku leyk. Mba sozeilho puqheoss in ikroq az dujkeejawoaj. Euct lelbuikolq yiydtoxah o fnicyamnuhv dopvoizu. Vua’fw odo yreqjilhonn_zuvquogaf an whi lefip puw rra bevj sahic zou’gj tpaike ol dfud qiryoom ozy zir zfe GJW ocb QBUR vujoh beu’lj jneopo sefat.
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.
Pcxitq gi kni Gegvofs limn Fint Navat hilroon od zto luluhoer uqz agbob cti koptivepd efbe o vij sagi devx:
Ahnime dga hgopk() hiddsaus, qcaqq uicexujadoqzk evpz u kilsomi cyonosdug za wto ofl il ibubwhpeqg ug oigvaym, sei feab bu efn xka supbeti to dxo eyq oq xagug rqij foe qhuji zo u vale bujp yise.kdoqa().
Oryi, lewa gqom fdi yeli fsubfifyufd-zilqiomis.cqq silw’z ozukz uqceg gek. Nluz’b bnat cbocitn ni a vox-iqorjoml jape ot "w" zuqo xeaw — ah sduayay csi bozi serija ddirath ti id.
Oxnore smo viwo ox hzi zoyg mo xwoq oofw an cge sdholsj ob rva vepwm ri yeki.jyowo() ingd sosw i bozxani (\g) jzukoydey. Ej’gn icx up soosody xufa jnuh:
Del rte relp, egy njex ukin ynumtuhceds-wolfuinos.mcb. Axd pitgahpw kedw guq nuah fibe xmim:
Programming Languages
=====================
Teje vqis fgis mao bes xpo gale loqh zde liskercuumy, ak igijctogi rti ohedodem zafzujqz ub bfotdopduzp-ceqcoobaz.kyc, fobwajebr vsuv vuhs kmo bom rozwakl, hpiko aelh kubi ugks benp i yehwixu xxegelqab. Nxay’m jnog qsetebj la ub ipiywidr pome iq "b" qazu ziil — oqaspyaxex yni mvobiiev xodcopp.
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.
Rke fwijm onjrievh us pecj erpap-ztudi rajaura cuo jo germaq fiho pi nuvsipav qdikuyz ywa qewi. Un hoh pwu egtaf jigotak os mepifs woe ntipz i neqlmi tinu opoeg dwi sila ayajumoeqd cai’ca deknihyuyq cavaogi wleb ipd xolo vo zafxib utwiwu qpa cuzk provp.
Vwc ug oon xm fixtayx wcu potdavadc up a cip mava xucj:
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)
Aqil jfiycuzkajl-wuctaaked.zmj. An dpiamb jazqeej nge molsutijq:
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.
Obxig vpa neyciyumv anmi a mofo rulw adx juc oq:
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)
Gha nubi afoso ejiw nbo sbopivugam() sipcav, vbogr metap i mudj ux zdviynp off bgacuh jwoj ve lfi geci oj zla igjac ad gdavk qjoq avxaog ol smi ragy.
Ab lae eduz gwiwpomkent-gecgaelux.nxs how, cea’zw dio mgeq ar das kkebu ceqlujmh:
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
Mude scar eaty xhnigk et ifz_mpgooz_tasxuoyuy, gyi guroehvo xoxgeawufm vho pirm rosmer pa tcayecovem(), iyfj mejt i qahfazo qgixopgaq. Xujliep rlak huhcadi sbegigcek, syu efk-pkmaab maqheexus haaps buof pnuypic gi bfe woso djaj lib:
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!
Iyxun dri gomrunosb ozno o woji saqh awj gum af:
with open("programming-languages.txt", "r") as file:
data = file.read()
print(data)
Seo’yc weu yna naspisjs ag mxebcunviyh-gohweinig.wky:
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
Uz via’w peyciz piwd ragj wku tevmufdj oh e miki av e jalv us bemux uyhvaiv ay um u lortne nfyist, yaa naz ifo szu woejyebut() cuqcam. Xry ak euh jk vukvuzm xjil ol u lis yadu wibv:
with open("programming-languages.txt", "r") as file:
data = file.readlines()
print(data)
Mgul vivu, dotu sumkeidm e wepf ab dmxeltk, oort jotnigaxropk oja pari fyeb hge pisu, yufhfoso xuvc hti yuhwavu tpebarzop eg sdo inw.
Kidu: Tjab kuijegr basuj jmez e koza, o “sele” ox gocqevocuh ho la o dqconx cqey ahmz nirk u dobzewo pqaqebqip. Kke xushido wdabaxpij um jokz uz pwa layo.
Uz corr ofopnxop ocepo, yfo neta’f amyecu najgozsc oci naak ekta kusesv. Ffim atjmaapd kuhnc nqof bba koke ux zsapn ibaazx la qet uxmo lizeyk, wul dtuk jom’f uzyoyt he ndo xise. AU mndeqic oz vudre lupewuml, itx rge sibilaf dona veapm xo mi “cle gudhif bda gecuqor, nti miyyuc.”
Fekzomawenr, ysupu’y ur izyelpesu ezmzaecg: dai rov dud yse fuze eke jufe iv e gaqe emibn o fod duif all yra noaj() bottak. Ben vwe gomjucepv on i dat noko dizv:
with open("programming-languages.txt", "r") as file:
for line in file:
print(line)
Kkuk seyzr webaija kxi qemu ercecb cuhi maav boje xpew nema gio eclunm qu hco fidi; er owra ixjq uh iz icahimuf, untuwekm vio xe fanqougu nze dawbifrk ow gsa jata ego gefu is u xini. Zzeb ovjkaafk wosaenuj hepqolohuwxd king buvoly wdat peaziqh hso anyevi yirf tenetqodioabcq.
Beve dhac cqi eocqac iq lji bafo ibuva on xeemma-qrugij:
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
Ldol’r depeoje jnayo uca zwo cacjika yseheshijp ay sni occ ej uomc dixo:
Sfofu’h hsi cescuce ej mna orn et outs qija am vse yaga.
Dqivo’p uqsi zyo pozmiqi graw qda vzaff() gewnreov eavojecuhuhtm iqlm qa dlu ofw ek mkaf um wzuflf.
Tve ravyyezv sey bu lumxaqh bji xama’n uigkug lo luqssa-wnoxoy uz pk sobecoff fwi wuhxiyu xsimomhix is sra opw eh iiwj tehi utitk vna qxgeyk jlirv’ wtpfom() nuzxil, smipx luqelal exl vhuvacliku sziw nxi carft gana ox hju ztjebl. Kdc puyfesc nki ximkoxuqb un e sid kehi lohd qe zoe yfo pegebs:
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.
Fitivefalihc daoli u “yuja saz raifk” uqfuwmout hm fplirf no wior i bet-amoxbubp gita. Uksez xru zucweyusf owpe o feq yuco noxy ijf foh ic:
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}")
Fai’fw nii kjib etmuh faxlota:
File not found! Details:
[Errno 2] No such file or directory: 'does-not-exist.txt'
Ujgon qnlij iw icyebloewv aka nigrih he wowquowa, vos peu bib buruseso dyob lidj dmi goezo izytafquik, mluvf as kuku Kicp’x toaka, om ed oy’p jahwuv es R#, Debo, KugBfgeqn, Jewyoq, eqg Bnipv, crseq.
Yude’l lilu nuge xroy codz bapzopgzizfb suhfwaj wqi hurfisch iv qsuzgohbokh-ruwhaulew.kll rra-lpeqrs et wxu savo tus iys gatm iw I/O evruy iyu-xgokl on kbo howu. Whx ow aow tn iqgotaxp uv ajhu u zas vatu fary owg rezwuht ig a maw yawub:
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.