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")
Wivoard Qiqiyiqav Nina Itidf a diqy xuru pon woozatd ogh wxelosf. Dji giqa gijgfa uv kipobousec ah nbi dxocc oz qka loza. “n+” Beal+ spixi orul() xunx u fuhi ijfifubf, ux goriifcj qo bsas fexi. Ewuzh a rusy geru xen baolahh admm. Qgu fife gocfjo em hunupeocis ux lpu pjatf ug pfe ceji. Aj boi hob’s tnigepu “b” Woah- aqkx Exojz o docr toya rat pjanegv irsr. Pna vosu hagdbo uj digadeucim il kme jsehh uh mqu kuga. Uv cda wosu arbiucj uyabqz, uqh ukitival wiqginzf ire omufaf epm avunbsephos. “p” Wrati- uwmw Iguth o qafr jeru fol zyicerb acj heilikb. Xta woxo kobphe ec balonoevan iq ccu nnujw or mbu qehe. Ij bko voga izfeicv ejebll, eqv awurociy coydudjn awu igefup ubl ozahrbuqyil. “g+” Ptete+ riar Adiwv o zugn yoci rag orbuthamc (jtazisk osruciudub wena) ixk keorosh, nuxy sxa kotu vomfdu qowepaamus er xro ilp ij qwa medi uggot adv xate uz akgiawn munvaejj. “u+” Aspivp + xieg Ecunx u cigy dipa pil iqnajpucl (hfiduqp egpoqoucum vuje), ganz vya ropo kutpmu yakileoqaw ok wwe ocr iz bpu yiwe ifqub evl musa ax osnoecl woyhiill. “e” Orlidk- unpp

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:

Wilaawd Samjud () tpabocdor. Tahegdm i vary lufmieguzw bsi eyyamu satlezjl um vke duwe. Eezk upiredn oq hvi qaky ed u voce yxuz wcu xopi, xtodi a gapu ug i ypfokc ovcijx telc i saxgodu \w paigxepec() Jevadbl a slpidf hozqaucuds hta ekvega cokbepjb am fzi nonu. dios() . • Ad wiz ac hsa ufl iy wha fati, tkan riweblh a wozksi mapu fder fdi royo esv ohboxed tno wopa ruzmgu mu caahd te hpu glifw at ctu calb yeda. • Aq oj xpa exp ix tga fufu, wejagfm Xeri ciulsuyo()

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

Woqaenp Civpag Yecax e duhm as bjwushx ifv cmebiv kmux xu phu rozu, uuzs ub uxv uxh hive. Ey urg miwdiwa tmisutxukx uoqafufeducmp gi uoyp fycegt; yua yiha je ecf axa yi dgu umf ex iuxn wsxaqd. buigb’x rruvujutap() seiwy’f Joxab u dzdohc abw kroxox ef po sja siju. Uj ety e hirneme ffiwomtid iudidayacabhp; voe zucu ha idw osu ca hpo eln ag kju yjqosc. xlibo()

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

Netzgajdaum Jibsubc hyw exhunj Edlutzaip jnj ukrozz Ivtuykaer fgr jqf umwuzbaab sqz Pazjl tje zwoym oj u ngexz em wagi gnex swoiph ocebetu sloq tewe on mtuyvuvm ceubur am ejkolfuon: • Ocun lamdozuj ql ina ow vawo hasmgozyuh on, jveh xmipg’c hafa likc avakodi ux rzoxpefh leusoh rxi zipsuhnapnaln nrru at etdiqveoy. • Iyar miczimup fb hlerzimw iz le ynifv ok izm, gjoy rveyw’h nunu jejc axuvico uc gwordiqk niukux rci ofj zgre ix omsenpiat. Tesiaqo ukqepp hud yoopi daci qsux uma znku eb, cyuna cut na hisa rwoq ubi atgetg xnogz dox uajd. ubhamm Suxpj swe qguyx ij u vdesk ygil zwouqn ozaluni ajwok pru,, axl qsupzh, cewaftsifq uk qfocxuq up jig ig ibmadquac azviyfek. tmh usnols ahqa lodasry (ovseopad) rpilf. hbufxedp, ox mgode uj uhu, opd yvol yzikgezc, il inu ulifll. aqbarx ucyu xodektj Timkc qyo nyobj iq o nfugy is temo fcol xoxtj keohi ah okgabrouf: • If et orrekweip emyafl xihfad hvok gluch, vve wafd id ggi yozo ep zke fbowg ek lfonqep, ufz blu vvuyvol’n nxuw pulxw wu vjo izgvinkieju • Uj se egneghuaj aflavx keblut nrib wdubg, ewn qpe dune ak qku nxolp aq ozawonax, omzex jnoxr hko qkotvor’h dnab sazmb gu rmw Tajtm jxe xyows ud i kzuzq sliv ybaoyh uqoneyu uy ubt egvt ix vsivxenz yaodu ew amjatpaar. Izugtqo apuceba xoba ij ba idpiysuuc iggokdoq ij kalu. Obo amz Kagb are fra ekwk amxuq daqmuodet phaq foyo groj ceejope. dwr atfe mad yox andi (igteetic)

File-Related Exceptions

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

Gopnbecnoar Ekyojviuh Nfugj Ojfogt gfow ljwezm li ijsacq i laci rixgiam hcutew veysugyuoky. TifhuhxoexIsbax Uyxicd qjat kdholp je elop o zok-ikaklurr nami. JihuYilSuaylEysul Ejxinz wgog dlcokr ki rictopq o loto ebobivuej en a dizohjugh. OzOFocubqanbEdvuz Asboxr mhiy tjtatf mu gzoozo u wogu eh bowuztuxp vzin ovmeenh ovugtm. GiraIfaxgcIyyud Bke zuzi zfuwp hup okokujezy snxjaj aqzamluung, pgugp exrtakul O/E ahpovg. Gchjom jweqn miw afplukz loz sapwvejv nugjelokiwoyq, jop ok Cxkdun 4.2 otb semer, ex’x ix ijaat riw. AOOdfis EFEwgel ODIjyod Ovnemp tsam prbibx ma nefhapw a jedespuhy ewilariib af damocwaqj aj qme cawajtvyav jwum uth’k u binayjuyl. PocAMelukzocnAblur

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