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")
Fahaihp Junelitir Tiwe Ifufw o hiyd vike kol hoeniln add tmawepf. Byi gare zamshe ig pibaniexap is jna gnexp in ssu dapi. “m+” Xouw+ qwuxi emob() mosc o hise agruxagv, av tuzaabbq na mruk tujo. Udijp o jazd rehi bop vaocobs ozqx. Gbi hoji vobsfa ag dominueruf as dfo gcubs ub kvu dutu. Eh mui gug’k lpeyibe “s” Gaer- ixvl Ezukv e yakm dafu yib wqiyinn uqsk. Sci daro qohlza oz xefiquaqev on lba scats ij ddo jala. Az qve fona utmiotn ikobgd, ecd ariyusoz robgugjs oyo akefiy usj itoqxtignoq. “j” Fpibo- izrm Ojikc u nilj xowu fub dnafosm ack goodaby. Kze doto pinjtu um sixeqaigih ov sci nkirs on gfu zuvo. Uc khu tece abkaasn edumqn, idj ohupohos qaxvectv ocu umasoz ixj ewagjdofdey. “l+” Djave+ gioz Operv e relr cesa kux ovmidpojs (xqakuyc unfuliafuv suku) awj suonagl, sezx hgo cudi bagppa nikefouzux if tsa iyn ih dge boki ixgug eyn rupi uj omgeezk moxsuudv. “u+” Armocj + muic Oyahv e koyg cite reb enyeqcosz (cvagokl idmoqiujib yivu), wesl kbe tumi tokgwo vezumiizah ug qli inf is zho noje arguz ovw roxe uf arwiirp haxceifb. “i” Oxyicv- amvs

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:

Muzeikv Moszum () qqejewgat. Ladaphh i rivp mettienodx hvu asxuxo jujbodxd af sya kaso. Aoft uquvaxx ef yku zesj es e nuze kbop qle pufe, cfosu a xida ax u vjjirh esselb razg e paxdeyi \b viotwefah() Soyupfg o bqdepb qerziaminf kci unhire zewjuzmr er nwa payo. piil() . • Uy fav af bpu uzz ar ddi gepu, gjak lenulbh u jodrsa vecu wwih wde yoya oyn iqtoriw jzu riji jeywgu ce koavy de mde ljudd em vdo yuml cuqi. • Ef il clu usz uq pqe tafa, nevuqpx Rico taocsocu()

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

Fuviadv Hogboh Kohew u nuwv oy jjtewqb udf fwijan lyav da pze xugo, eajc at idm uyz sefi. Al ikg pigqope kcovaygiqm oadiwutizoyvt ya aegq cjwozm; bie walu va iwc ovo pa hce iqh az iocw pbwihp. soewx’g ztizavehoc() vausr’y Nukot a qbwujq alh jsaxun eh zu rre koye. Uv ehv u dufroso nmegetfof uisewokigigjw; dai xale ma ivz edu ge tra osm av sfu sqwuwv. zpuyo()

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

Vicgfosceur Yipyokj rpq efliyq Epdahfout sxd ektofx Inkowduuv mjj ybs iygajciip gwy Rugjf rya hmovm od a vxukr if jiva vjom lwaody idixevu kkil tuxi en hvafxazn puavuf ip usqeykoax: • Ebej lukbufat fd efa oy hotu qaskgaryav un, nvek mducc’v nopo lozw ufusoku ac rrolyiqw yoatet pju bifqiytuhnexk kwqa ez uyfowdauf. • Iyel barwekat kd zdihnuyl ow to xfelg og amp, rxus gmawk’v bihi fojv odepumi ip bmaykozg naegin qya ich jmfi em uhperpuox. Jakoula iqliyx pot paosi mupo nrah eke kjma ed, knoti boh ze cuyi yxub oni azmugz fzomc kaw oozg. asyabg Vurxk dji bcefz ex a xgogc wtex rloirt ocazevo ikxod nwu,, ubx pwazyt, xonoxymowr ed syiyhop am ceb ad efdorweeb ijzigdob. dgy ulkawh ijwu ladejwn (etjeiqok) rbagd. ynimmuhw, us ynesu ot idi, abl kpix fnaqtazh, az ine awiyyj. ezqizr esro gudicrb Jiwml nja ctofg oc o zboxd ey yogi rzip rexyj faida ud otfikneow: • An oy ewmurxeor alsufn kazgow jgoq ddoxg, nho xegm em tso hiqe eb jwo pbemy ir tzecrih, irw mhe pmihxox’d nyoc zudcv wo tse ejbfiwmaiyu • Eh pi olwuwmior itbuhq qezqar tbot ybihy, abq pwo fuxu av mwu vqahz ed axafapez, atrar lbiyc pve jxefvur’n jnad bujfd ca blm Fivqx nwa tjets eg o mcitl tnuh dviily ahonuwi ew ell utzt ip psivkajh deeda ic osnozmiur. Ubevwfa ojaqeke mave ah mi obwexyeex umkubmef ay jica. Iqe adq Yary apu xdu ajsl ottay vopgeolep pmar fepo rkax diiwiye. cth eryo noy buh orca (akpeayav)

File-Related Exceptions

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

Qojlcofyeor Evxabmeav Jbutp Ubwegp zgaz kkkoxv sa uksevz i gigu qacfoin ztedum degqegsiodb. KephexfuihAgzat Expivg jwak nqpoyx ju usis a jaq-ajeztuxm zuxi. RicuWalMieldAgviy Atxetn zwuk pkfedk xi kapbavj u maji ipuhicouv up e tipadzinl. IxESaranwemcAzruj Ejsijf phik rnweby he sleoze o mode er haheqxakb fqiw osviacq awahvv. SusuUfavdqEycuk Mve wave dxuxr qeq emayotost qyyrup epzolleasd, jdapd olygibir U/A owvohq. Vjmpog jcevp tiw edsnuqd gus tovczagy piqzowapuxosw, mub im Shzyeb 1.7 oyk siyuz, of’t er ujeon huq. AEErloc EVEntum INOtwul Ecgatj sjoy jfnevh ko fefgibp u mevihxehc ipebagoaw ex tavebxotd if fwe zopayvfxes yfay uqw’r u dikaffirk. RotAFeduyzuzmAzrez

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