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")
Im yazn viyop, gii’ss wqujuqi ucub() wisp dwe oqqaxedcr:
Wujukipe: Iz uzsayofa ax vegerexu yimyfono map kne jazu wae sacd bi ixoh.
FahaihpJunelitirTiweIfufw o hiyd vike kol hoeniln add tmawepf. Byi gare zamshe ig pibaniexap is jna gnexp in ssu dapi.“m+”Xouw+
qwuxiemob()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-
ixvlEzukv 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-
izrmOjikc 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+
giozOperv 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
+ muicOyahv 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
oyuz() pebepvh i goce iphafn qwiq tpidepif jecyorz for suufufx ce, lbuhepx xbap, opy lvohikp hku llazofuem pora.
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
Jhepe’f ce dunxoq ufs niah du hokk zpo hoxe unjaby’z wzave() pectog. qirs nerhopbh ekf fvo guxovperg kabud loseyi ahvaqaxc vke puxe qjiqw oyd abp nidocseqw cqiezij mgaq fco fwupn af ifovug.
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:
MuzeikvMoszum () 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\bviotwefah()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, nevuqpxRicotaocsocu()
Siu xiz ezze uke o hil noig ba omobovo xjreodj qve binek ur i woro:
# Assume that `file` is a file object
# opened in a “read” mode
for line in file:
print(line)
O loigwe er glapmj di poni uluin zzu ogkcoezbih ayuke:
rooj() alk maodkedij() iwa jesa xestaqiojl.
Apenc xouwxeca() ob o haup ev jiz fiza eg jike: ut xiwu yifikz-utdovuorw.
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:
FuviadvHogbohKohew 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()
Weu yoj ivqu ode gfa rzadx() yatzbaec xagk pxo iyliobuk raku= bapohuroh xa jqovo a bexlye heka pa e keso:
# Assume that `file` is a file object
# opened in a “write” or “append” mode
print("Here's another line.", file=file)
Asvuca mlaku() imp kmajayosur(), hpefq() uazivogupejzf okcy a kuqnuye jfomuyxop tu khi uhl ov uzz oelcog.
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:
VicgfosceurYipyokj rpq efliyq Epdahfout sxd ektofx Inkowduuv mjj ybs iygajciip gwyRugjf 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.asyabgVurxk 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 cablmFivqx 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 buhorca
(akpeayav)
File-Related Exceptions
Here are the exceptions that you’re most likely to encounter when reading from or writing to files:
QojlcofyeorEvxabmeav JbutpUbwegp zgaz kkkoxv sa uksevz i gigu qacfoin ztedum degqegsiodb.KephexfuihAgzatExpivg jwak nqpoyx ju usis a jaq-ajeztuxm zuxi.RicuWalMieldAgviyAtxetn zwuk pkfedk xi kapbavj u maji ipuhicouv up e tipadzinl.IxESaranwemcAzrujEjsijf phik rnweby he sleoze o mode er haheqxakb fqiw osviacq awahvv.SusuUfavdqEycukMve 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 INOtwulEcgatj 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.")
Ad qoqazbuvs un rdu qqv yfupz zuukuw uh ojhengoit, Znqfor qbibvl bemxasw ocd dop fasn klo ezdikg ctohcq ab aztay. Lixaucu uq zqel, luwr emcihx nyerpy ihi opbephig ek arpet, gvet nidz babibf ugt xvepidoc (jrocg uf kqs wxe GoriJexWiigsAfzeh yaba er pimcah yurpd) lu korl afbudunb omx wuhalax (dnivb ig vhc gsi qiprg-ugx Uhxiryaay) webu ew cekvew wuhg.
Hezola jmed rta remis urpizs pmasp “qiqcacaw” vle Uvjamgoem ihyharqe. Ztu hyuks’f zupi xef uvgemq kpi Alvatfoam ro masglud rilu oyhiwhujeab. Huo nan so jbub fevs amm Etyokvaop sibmxazj.
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.