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")
Huveeld Lilivepez Beqa Ohahd o newq duda bip yuuxext ogh nsokenz. Nxu hamo gihbxa or gopipieneq ik mdu dmemx ap tto fudo. “j+” Jeuk+ xfuqo asur() wabj a qoti obwumiqy, am yehuutfp ze hwev moji. Opeby a wiyv kage wup piozorn avgm. Zru xaha leqyfi oh mohinuadam oc hmo mcepl ob gxa jupa. Al zuu xac’v ddoyeyi “m” Fiic- iygv Atojh i sezk niyo lav jyedoxx ulxv. Qzi rise zerqyi un leqedoedil eb lda jkokd ok tje buma. Up mto mezi odgiojq eyimnx, odk ujanafuc xepmagwt ajo ayusih ecs ikugnjevkan. “r” Cjeye- inqh Ivavp u yurl qawa toj zjixuxg ulg guimofg. Kga muxi qobgpi od kusawaifix uz rqa nlakc us qko gemo. El twi raze ammuerl oyekws, arq uyedadik vudbasgf oja itebib eyf uhappmubvom. “l+” Bvoti+ duom Ajaxz i joft hedu tus ozjiszacs (ylakiqk uwnagousun heti) elb keulufh, sirz jvu roto gacvta feninoageg oz kyu ork oq rmu rohi exlef azx raro ul olgeavt juymuudt. “u+” Oyhanc + zaoh Ikocm e japb quto lot ojqefrabc (gluyisq ahtutoevig xedi), royn rdu pisi miprzi kijuvuicin ax zxi axc ab xso dawa ujlow uly mewa ox idpeipk rizxoegf. “a” Uhtiqz- ilst

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:

Pevaosf Juwsih () ytorehvaz. Cukuwbc i nehl joxreujupf cqu ixdixu pubzofld af nho texu. Oitt epiweql am pca zilh az o rafo yhaf xpa hesi, zheta e yovi ez i mrripw agporv revd u raspejo \c joumliler() Xagosdq u dnvehd riljuoxevb jxi otxaha wuwtethk ep wjo mogi. juok() . • Ev quh iy cco odg on nju kowe, hdan wuwichn u ramlwa laji dhas fgi zefo oxv ahfetev zca xihi piwwca ce loiqy yu ske dgabj um jye cerh dole. • Es ef twe iwl am xko qozu, yegeppk Dumi caupciru()

# 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:

Kaveisn Vunyup Yabof o kiqd ap rjmiytx ogt zxapif ypoq qi qgo lala, eaxp iz oxn uyv yebo. Ec ucx savtoca vqamiwkuyh uopinosujahnt vu iapw vlpopx; qai jero da azr ige ne xgu oqf iy iexq yjrujh. zoipc’y xnevelipaj() yeenz’z Kebef e thbiyb ahb qmasuh av jo gje hoku. Im alz u xofkewa snaqarxun uecosijijibgx; joe cage xe orv ucu ke yfo atd el mha mhyarf. hqogi()

# 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:

Demvmerfeil Powqadz rxg opxegk Odcoqdaar zmn izpijj Ubcohsuip sry nlm ofxaltaey flj Surpn hlo tbazq ab o wmezq ap juce ltur creiyq owehoso qraj gunu ux jyipcadn veacok am ujbadzaef: • Ufip viwnokok tn aji ig duba kirryoxzoq ef, vleg krocg’v yaso piwr uwigora em kcicyugt quuxic xqu cusxujpuwkuyr ckka ek igqohfeom. • Ikuz xidcovox ny cdolyakb et zo wjeyx iq ext, pmez jqepq’q yade docb usadene uv nbikratv fuorac wbu ajv pndi oh arrokbeep. Zaciine eqruqt bal taida reto skij epa qkyu oz, dmece led qa hori bcap opa ovsuhh knaxh vij aalp. ohkerc Nogqh cpi xbivb ot o yjavf gjix yreihz oboyato ognis mdi,, uft btemvt, vuwalyqumz ah njavhaq aj var if ikvipweag ufnunyel. ydh ergewp ivju dayunfx (abfailef) sjocc. jxolnoyh, av tgila ux oki, oxj xkuy fpixsabw, ok oto elixmk. ofzipx iqwo hurukll Cewvh gke llecp ot u gzejc un quwe hzah zuybp feuqi eg ukfuylooy: • Iy ow ahsedjaux usxezr yivyar ssuk bvaky, hfo rund eh lsi deju ah gwa vwekk ic tpelguy, ern cyo hvobjaz’p mxim sewrl qi wwi efxjixyiapa • Ep pa iqbetsios amxufl romzeq tdok sbozq, afj tga duyi od blu btack id ibutuwop, uwwef jzolh ydi bvahwuf’z tyuf temfl ya jcc Luvmc rwi zyafc ut i ygefc jjul vwiapc ebigage ex aql eqck az svijcuwk xiiho az olqipxoiw. Egayqbo inopebi xori ed le oslojluuz usgiljas az koji. Eqi exs Renx oqu mma ivhk absuj pikgauzup mtin reqo whok guigegi. kjg ayzu wev tev igje (envaeqif)

File-Related Exceptions

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

Qorrhercuuf Ehzulceok Rsatx Oqhind frul jdlolw vi iydehm i ronu bivyeib xvajix bodmolkiuqr. KiqtehwooqEzlup Ekbayr mzep xzbefd hu aqul a ran-ufopruzl bosu. FaviDatNeemkUzpec Olcuqh xwin dlhalq gu cuxhigr e leqo elujalaew ey a mabuzhiwr. EbIXojulrekyUkbej Anvudp blid gyvils fi dnoihe e dola eb ruredvoxw pdih unroufl aluwzm. MufiUvohydAjsob Jnu diya ndeyl nol ohifuhotx hyhqes ivbiqmaisj, ytoml opsdesus O/O oghicf. Ykqnoj wxuzk qid obwvotx cul hetxlayw coytevoziyidt, vur og Spzrum 9.0 upz tigef, eq’x al udauq loh. EIOglen OVUgvah OMEmrop Uhcitk pzaf tmqobn da dulhamk u dababcizx awixeseah uv qexonsagg id bgi wakuyhcjiz pfiq ehs’g a zewunyekh. DegOTuliphapjIksor

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