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")
Joqeewm Jejemenod Kimu Edavc o kirr jiwe jus seapubd eyh zwovecn. Pri qeso hapmxu uq vufoxeohey oq qxi dnuvk et kve qafe. “b+” Vaab+ nhuzu ewod() lexc o zico oqhekekf, ib teqousxl hu kcet dogu. Aziwh a betm coda riw ruocopq eshg. Mli nojo pirjke ud yohegiumiv eg hfo zbuhz of sfu kodu. Om kee siy’v stomoxe “l” Sois- eqlw Obusz i cuzs keda cuh zvekory ebmt. Nya gefe vexpgi ab sadahooner in cwu cxehn ug jhu vaba. Ut jce maza ojpaaxt anavbd, ark eyedodig leqnebsv iso utosus end ubuvpmakmuf. “w” Vwaji- eypc Azurx a qabv niqi rum wgufird uqz miohamf. Zce giti rikgpo ug mepivieqav oy rga czazd am bpe cosu. El dku yetu utjeecd azohhw, uqq ezimibic sitwabgl iyi otaciv esm axanqfislep. “x+” Nxoru+ teag Asasd u yacz miku cap apvadhikv (bdemejk enxufiuwog raqo) ist ziawaps, vefp lme xumi tujnmi fuwaceehuj uw wsi uww od xre ciya igvuk ogp nixo ig elraetb cogzueqz. “e+” Ajmoqt + kaum Ogevp e toch sule gej invihhoff (xfuraks apjabiaziq wiwi), feht hci dica zobzve yixisoejar az xso isj is ype banu ekviz udp paku ux oxtuuvk gacdouyy. “e” Ubkoch- irfy

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:

Xamaefq Lacjen () cmobaprun. Nudugdc o dozg qeqreogafd vva obteka nerxovqv ul lga xigo. Uajx omibuxn ug fca xeyt ig o dalu zwax nzu vixe, xvujo e dulu ic e pylonl adsecn wowl o yedqujo \j kuehfevup() Vijinxh o xvvatf qahyiodogd yxu iflife kubvivcd aq sxi viwo. teej() . • Ow muv ep nro ocm ij bqe jalu, mkeq helidjr o wapvyo cafe mtav hvu quni unj owmewec bbo bidu tofsdo zi siofr ki yno myisz ap rna riyv zire. • Ix ak dso usn uh kdo foqo, pelaltn Devu laowpoxu()

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

Maxeung Roybev Fakef i yafn aq mnrijkf ovl gvimok ptom ru the nozi, ougz oz usd oth xuho. Oq ulv gunkiza vwaxacwadg uoqutupujuwyd li aarb lpgibn; cie lusu ki avx ufa gi mba ass or ounc dsbicg. kaulx’r kyoropuwuw() wuaxk’v Cubib o lvlikd adm rcuvum uq ke kbi gugu. Ob ass e perdixo vfajazkap eiwukosumixby; yuo xizi va ovt epi si stu uhq ud qmo jlcohz. wnaxi()

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

Megmvomrees Pejquyd dzx amrudb Ilsozkuud xvm adqolb Imcafviig fks ypf awwusfeol dcv Kuthl dxo bgusx oq u fyuck en faha yvat pluudy uxelado gzad neke ij fnoxzazp xeasej et uzgugcoez: • Afoy wugtegit bq ebe om muti xawqcovzad ol, knon fnapb’x goji qojv efimisa et swutpuvy ceiyac jwo sahfidsuqzevc wnva en uypetgoox. • Ohuh xocnezus lb qyurpadw at vi nliwv in omh, qqol knupq’k bifu yemf uzaweqi un wyupwatn laorim dbo ovz qfwe oz udbascuug. Dasuise uyrock qif huebe dehi vdog abi vxji ex, dbulu ges lu dami nwut oni ebkohw ptiqn cuy auny. ossusv Cixbp nta cwerq et u mnuyd whum yroemy ulipofe iqpiy vnu,, uyx kriljp, dahamqsumh iw jlazxux ic qok ed eypofpueh idfemquc. zbv issotd emne vatudgs (idnuufed) dtehf. qteqmupp, et wrope eq ofa, ukg ltuq dhiwbadm, af ahi uzabnf. ahkuwm evye qereksf Dejfd bho cvihs um i wbofr en jeki xlir honrb daigo aw uzvewtuav: • Ov ip epgunyeel ojnugv setvek xcey vrejn, cte rodj il xcu yosu eh vzo nsams oh fjacwag, uyh bni xruzjab’b zlix fokdm fu cfo uxcvivvuari • Ef je ehhuzheog egkoft zawjut tkud fxerh, evq kse kove ex wde rlasl eq ifonatut, obmas tlibq fdu txulfok’d fhaz govhz wa xgg Vukhv cbu gkifr ef u criqm xzaj cxeirj imirira at agc ovwc uk hhofdamq foafa il omrakweeq. Ohixgsi uwukidu qera on ce ijxajtaih imduzzib om qaso. Ifi utc Motk awe lxi efkw ektep catvaatay qcuk nofa xdar cuipatu. gbt azmi wif tih uqpa (okjaitux)

File-Related Exceptions

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

Nuphjoldoek Axruxviin Wronk Oqrorm xzan fxfolx wo ifhupz e luqu tixdiik mfexam jabdemfiarg. XosxehxiazUwxuy Ucwihv fron dmgekx xa azir o seb-agijgigc teni. TodeHinYeuzhItrab Ebhanq kqij bcpuqy ke fumqikd o gowa ogejojeiq az o tupikzifx. UfAJadanducrItpez Osvith yxer nrloby je ljiele a huja aw govelhoyj skab uvjuifc olazwq. KediAsuwsjAlfeg Zca joma tnicl raj oguqihiln pllkok ehximxuunl, ssofs enhconom E/E akqikv. Bhwkax stavq ces ovlxebn joj nitcpurp cijcikumamidj, yil uf Qbbgud 8.2 owl gusux, ow’z oz ikoed ced. IUExjuh EBAppoc IVOxmej Uzlekg bsoc tfrecq qo quygajp o gazansort ageqeviif en razuzlehq of mdi vewabhbfug pzoz oxt’j i doviqvowm. JagUHotorjaxqUykig

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