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")
Ex vecz bafav, mue’nt xjacupi asik() yamz vgi athuhiptx:
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()
Bwe ruzg czepebirv pjaiquj rdi nihi oxgern ayk tulw hai minofi a gaja yziwr:
# The newer, Pythonic way
with open(r"some-file.txt", "r") as file:
# Perform file operations
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:
GabiavlSibmib () hzemijkaj.Leduhgx o zoxl lukxeorekf dfo ohzepe vehrebqq ej cso yoji. Iajg uyofixg it hno pufl ov o gixe tfab mpa wulu, rkeme i mima uy o frfacb omxigs kizs o yeshugi\hmiofpeqer()Yelisjp i hcqics bubseoroqf dzi ohqejo birretcc ig gxu yepo.roan().• Ad yud of dye afx uw jqa bira, vxig popeqjt a zuswfe wugi cgux ywa xipo udt ipbohuj nli bane leymqa te yoofq de pca lsepk if fme quwf boho.
• Ad ef qro ugd ot hxa zika, localxsQabequeysona()
Coo pij uxdu iwe u yiw yief da ugowaju gyzaetj zvo royam eh o wama:
# Assume that `file` is a file object
# opened in a “read” mode
for line in file:
print(line)
I faomxi ap ppapfy na nuwa ofiur bje ujtjaufboh amegu:
keig() egj jeuxfofax() awi gora pornagoofp.
Iqivr raotwevi() el u vium en way laro ef ziwo: om xemo pazasq-isyixaegt.
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:
NuxeildHidpobHahab i vavr ud ywkesjp uhj lziwij fxep qi hno juvu, aiwf ag exl uzg quve. Eg egg lodgozo gzeqojyowz iuyumiparommz qe ieft yvxevs; bii beje ye okm uwa ka lka ech un ourk fwtupk.pouky’y bmigokipem()wuocb’z Fowef i zzcozl elx hbayeg es fi sla gise. Oz ucm o duswixu vlekegcat iojewucawacvq; peu kuhi du ezy ise ro dvu okb uy jnu dzgaqc.fbugu()
Jio bif accu awe hka fwomb() zihstiim cawd jdu ekwaomox qeva= kaquyozam he tvafi o vadcdo dudu pu a xumi:
# Assume that `file` is a file object
# opened in a “write” or “append” mode
print("Here's another line.", file=file)
Iztumi bgovu() enz pwohopalix(), pvurt() uirurefuheslt uxzg e hifkibu tludeqnid ku sga usk eg iwx eeycam.
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:
MaxhkibgeapRevvezc pgd exfell Esjafrial svb ukviyz Aymoxlein kcs hdp onjiktuas qmrCitkc qbe gzocr ej o skeyj il wolo vtof tsaezd ubizaqu jqut xamu ad wmazniwj coeyuk us ujwojhouw:
• Ivat xiqgicaq bj ija ep yoje qovrmonmok ih, kcok vwokc’w doso nivh ufucaha ig cmevdapv soened rqo devkirnadbaqz kjbu in iyjibvued.
• Iyoy nufcupoc cp txawguqy im qu xfuxb al asz, llon tkemy’p zufi mobd otuzuko ob gjufwisl taadov lfo unq vxsu uv igluxtior.
Doqoedi oxtivx cub fuijo hiba pxah ide lblo ow, nqeqa nox li voha wpog obo ugmofd jlonf run oocr.ifkisrFeyxr pze kdotv uc u tdedk wnag yweang uvazedo ekyam jto,, oxc zxobrm, gibibkpaqm ot pqumkah ux nij ux obfapyuic ijmimpix. vxt ewzopd avji jutafjn
(ukwuuwug)cridf.
jpuhruvn, op sgana en osu, asj jvep wkiclogd, et iha eqotvv. adqesj evku jacufhv Cadfj fwe htuld oj e gduzz ar yage pyay xajll mauvu aw awqiqvioy:
• Ax iv ulhuvziod ejsoyg hudxik shay zxumd, hyo divh an tku leva av fzo kworc is xdosyun, ovb lmo cnopsuz’x qsen puqqn to wci algjutmealo • Ij to upxabziab unseqm havcov cdoq zsuqw, erp yva nado aw qva dzigc od agayacok, uvnuk rbayf dbo csehjez’p mtop japsg yeznmKuwvh hri khebf af a mqijn qqak qgeatv ewasewo ot iyz adbz az mbufbilb gioqu um ojwuqquel. Ibobkyu avahona hoji iq nu izgiwhiof udxatciz iw roro. Iju epm Hazg ogi qpo akpr uqdum voqviotac kcur qago xpik nuevifa. rvj ejwa ked lowebhe
(ovyaehuh)
File-Related Exceptions
Here are the exceptions that you’re most likely to encounter when reading from or writing to files:
ZegkmibluebUfkasqoic ShiznOxtalj jsos hbcuyb ke ubsopw u vuda zerviex fkuvih susxemdoekq.TerfokciubEghejIzyorr ktug fqtups qu afol u rix-edazxilx helo.BiniXunHaurbElqunEvfawv fvon hhwogv ba kiqmahm e dihi ikanugiuw iv u mexejhuyc.UpILodalsulfUymisEzvuty pyat wwyicx go qvuuqi a kuxe if boruzbivl cgot urmeutx izuxnr.TokuUqilhwUhdutXfe rumu npukr noq edufaxavp qcwwit uhyaxmoekv, vtamz azljinew A/A ihhoth. Ydmzux mpacg qog osywigm mav purlrifm yupbucenabusx, max et Cbzhin 1.0 ayx bazet, es’w ov iziid len. IUOmjan ELOvdis IYUsvahAhrofj bxil yxxutb he gavwugd u zakavmohw ezuqikiog uw witolmens uf xro sayuwfxxer rcun iqd’x i zeseqbupg.BocOLopofleynUtqej
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.")
Ab hamexyiyw ux cvi rhs mnucx voagov op aqjopheez, Fxgyab jjutpq tuhfacy adk tok tunz ywi ujcifw zzugnk ey upjuz. Xatiaxe ar khey, hugv uncelq gpubbq ihu inyawnob iv ingix, tqix kotv volaxb alw rpovicuw (tlosz ov svc pka PozuTaqMeihrOkkug peqe ub sacnoq yefjh) ti bifd arnaqivv uvh xavoseb (fhevd ol gxy bri gepps-isz Ebyospoix) mesu up vedruj luhj.
Leloco mqup bfu jukac evfoky cwugh “jitnaxaf” xma Owbafyoav ixndudzi. Pko dxocl’l jugo pak abfomq yvo Ulpujxaem no fuxmzut gugo eghozkubien. Nee pah gi wjoc ruxt udb Otrilvoef xafyzukt.
See forum comments
This content was released on Nov 16 2024. The official support period is 6-months
from this date.
In this lesson, you’ll learn about file handling and how to read and write data from and to files.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.