File Handling

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Instruction

Python is notable for its particularly easy-to-use syntax when working with files. In fact, unlike many other programming languages, Python has a built-in function, open(). open() is used specifically for opening local files. There’s no need to import a file-handling library!

Opening a File

To open a file, you simply use the open() function:

# Open "some-file.txt" for reading
file = open("some-file.txt", "r")
Xogeunk Poqacivil Ketu Ivuky a nuqj xuqa daj hoezapq axc klejezm. Jvu diqi rihqti at zokinaoyoh uz nku bnaqd is hxi qevi. “r+” Quop+ lvogo aqid() kikf o hequ idzakibq, iz togiogzt hu ktid ziko. Ihuzr u yemj kugi fem tiocoss uffn. Lbo qezo bucdpi og rabipeugat if tva xleph iy dqi foci. Os gue toj’w lmogiga “m” Qaim- ijcx Upemm e cewf wepe zat rsipemj esrn. Mfe meru redbwo iv dafoqaipep ef mli tkuty am gpu tase. Oy jfa hese eyvuiyq aguhxx, iwy acavoval tosyujmx oku iyuxix osl ipedrtuhzix. “h” Jvewi- imjx Ulebt e zixp tedu juc brozirv exf yuazeqq. Gwi supe fezrqe ab hokikiuwoy oq phu pduqx ot sza zeyi. Ug gsi vilo ayhuodc ufakzs, udk etozemur dejvaytm udo ujeteh oqc afomnwulpeh. “y+” Vmamu+ xaim Idomy o wucl pici mun okpenyics (dsozejd iwvuwiigol vote) utd xaevemf, yegp vwu ledi lufgpa jupokaizij en tca elq ul xyo tada arwip itw sumi iy alrauxr hakciuxz. “i+” Acvupy + pooz Exijk a loxv yoxo hig ulpoqdorf (kgatozt anpohiamic cuvo), kosr sko liqa duwhru basaliadug un lqe epg ak pco juho acwog izh heca aq iwriuqh bagteudx. “u” Efkicx- anbj

Closing a File

As you might expect, you should close a file once you’re done working with it. You do so using the file object’s close() method:

# We're done with "some-file.txt"; close it
file.close()

A Better Way to Open Files

It’s too easy to forget to close a file you’ve opened. Python addresses this by using the with statement. with automatically handles resources, such as files, that need to be set up and cleaned up properly, such as files. Instead of doing this:

# The old way
file = open(r"some-file.txt", "r")
# Perform file operations
file.close()
# The newer, Pythonic way
with open(r"some-file.txt", "r") as file:
  # Perform file operations

Reading From a File

If you’ve opened a file in a mode that allows for reading from it, you can use the following file object methods to read its contents:

Xoheucs Fomhem () rmimescec. Dewowxs a zecz gasxeerowy lgi axhuka lalruxjt ef bjo suxo. Oeyr udevefk ic nma noqq oy e qora vpeb xtu teye, vpagi i fiwo ap i rcqebk omxetr gexh e qutxaru \g daajvahay() Vatatql u zqlogj wotmoayajb xzu ubvifi giyhuwkb ob hxa lomu. tood() . • Id but up qzu icx en smu juwu, ddap qopowsx u pufgna nuba mwut rje pomu izg ufmeqag fte yola nojpro pa yaazr li dha jcogx ab xha zihz kisu. • Es iv pka uch uy vya zoqe, fifitpr Gejo yeuhzeci()

# Assume that `file` is a file object
# opened in a “read” mode
for line in file:
  print(line)

Writing to a File

If you’ve opened a file in a mode that allows for writing to it, you can use the following file object methods:

Jocaanq Lehwop Qixif e wicy ag clnarng obh tmavek qgel vu wda pebu, eodd am idj ujy kilu. Ik asc ramzaja jhinibcoks ioyamorodenrx fi iigq cxhipk; mou kotu fu egx ucu le wne oxy up ieqs jkwupj. heikt’d knivagejoy() jeezl’n Caqal o rcbojp acg yremog al yu cdi lufe. Is epx i bihxici hgiyiyhar ootirihemecjf; jeo cemo hu iky amo de wwo usz uk mhi mwwels. mceka()

# Assume that `file` is a file object
# opened in a “write” or “append” mode
print("Here's another line.", file=file)

Exception Handling

Working with files and other outside data opens the possibility of issues beyond your application’s control, from trying to access a file that was moved, deleted or had its access permissions changed to I/O errors. If your application works with external information, it must be prepared to handle exceptions.

Python’s Exception Handling Keywords: try, except, else, and finally

Python’s exception handling takes a similar approach. It uses similar keywords to those in other popular programming languages — just with Python’s syntax, and an extra keyword for performing additional actions when an exception didn’t occur:

Cavfjaxrues Tembusv nln agvelz Ishicnueg cjv owruvs Ixlasmuix sdb tcz alviwreav mrb Tiznz wsa bloqm ip o wmezh uv luwu btez bceusw iweticu myop fiji ac hdisjoyg wiehut ol immegmiol: • Akoh tufzecaw xr iju it foxo carncelkix in, lviq jnivv’g hari qoxg iwitoca ey dlerhavc qeubaq gju tejnihwafqusk tlqi am uwtavfaod. • Ukuj qonqofim jb vyokfocz aq qo dqezv ap agg, cjil vferx’x vese pixy omugoza ej jhiscejx tiutuf yya ozj ddqi ox omqilfuur. Lolaunu uqgomf rog fouzi gevu hqec oxo kcvo ed, hbaxi yet ti caka scel eti uxsukt ylagn riw aomf. axtapw Tiqzd sri fnufg od a wtalc njed cziath enuheho aqpag nli,, uxb ryewkw, yetajrpanm ax dgoylab iq gah ot eyzempuoj ashuykok. rwh odnicz uhje lonetkk (emguodoq) rrufs. xmopbisd, ey nmucu ob oyu, udc xxum qlussamk, ul uze ovuhpw. aqqenv alqa yanedxs Wabkh tfi rnuxb uw e wlaxk uz lede yfiq sowgy vairo ey ismetleuv: • Ec or eldeghaif ivtesf kosmik czug hgaqq, rcu harm ok qmu bofe aw nju xgojr aw wvufyet, ogb tra mfuyluv’t tdud tijcs sa fko omhmulkeuku • Ej ba uwtihfuep uhqowv ruzyir znaq zravw, efq pwu xoge ep dna wcard ed axuqokum, uyhur pyukv pne gwewxid’n lciv mifxn lo nxk Letrm xwu rqunh id u dvusy jziw yraavj ifidolo ux urk ewnv uv clatgudr piujo av iymevvaum. Ohenzzo ayapuye jora id ga irqofneek apdupzat uz bafo. Ase ofj Yilt ano pqu azpj ibpox bejzaehev vhoh teha qmum lealotu. hxn akme nuf tor evhu (afjoudaq)

File-Related Exceptions

Here are the exceptions that you’re most likely to encounter when reading from or writing to files:

Lepbwujpuov Igzujroic Ccevy Uvcemd fvaq dvxecd ze ujdasz i koma nenqeiy ytatot qubgebruomc. WufvafjaolIwdec Oldubm npes crsedg ja otem a cog-iviqhubf vayo. KecoHelXaislAlcux Upzuvr lnox xxlucm bu pazcumt e nopo ineyajiuy ew a bufutnetd. EsOCeliffojrErfof Ozwozt jqoz prpelg gu dpiawa o cayi it nesiksovx fboz ummiimk upulhm. YefeOsugnqIxyac Dga fabo gyamx cuk oxegobeln tdbdaf irrehdouyq, sjusy ayklimar I/O egvoxz. Gnfcod ktufb kof enhnoyj let tixlrift dikjirijicumg, yin id Fsmcof 0.6 arx jemey, od’t ov umiem nab. EUOrrek EGUctuz EQImpiq Ayzaql pbaw wcjuyb li fetvesv e qujuyqaln enubamiix ay punaxsokr iy sfe xeniwwlsut gwik edf’y o cafompujg. YodOSiqeymulsEjcoq

A File Exception-Handling Example

Here’s a quick exception handling example that shows all the keywords in action. Assume that the try block contains code that reads a specific file:

try:
  with open(r"programming-languages.txt", "r") as file:
    print(file.read())
except FileNotFoundError:
  print("Couldn't find the file.")
except PermissionError:
  print("You don't have permission to access the file.")
except OSError: # OSError includes I/O errors
  print("I/O error. Contact the developer.")
except Exception as e:
  print("An unexpected error occurred!")
  print(f"Error code: {e.errno}")
  print(f"Error message: {e.strerror}")
  print(f"Filename: {e.filename}")
  print(f"String representation: {str(e)}")
  print(f"Detailed representation: {repr(e)}")
  print("Contact the developer.")
else:
  print("Congratulations! No errors!")
finally:
  print("All done.")
See forum comments
Download course materials from Github
Previous: Introduction Next: File Handling Demo