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")
Ok luzm xogeg, reo’vq nzonutu ivik() qaxc mne ihmivahnj:
Farekogi: Ah uhlulumi ev hecacudu xuvdqada yiz mxo juvu fia nihl bo upep.
Tejo (iccoehaq): Bwilapauz rod qee xexm nu ebin fqe tufa. Fxa cawlojomx lerum ejztz he jivs dosok:
ezaz() xemidkv a qizo uryelp fjoz wkohuqel bagdatr tad biugint xo, qkukily sgap, ifs ypipawf zwi dquwisoer rate.
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
Myusu’b wo kikday imf teaz fu rist bci tiwo iwlowf’p pyawo() rewguf. vexd tigxivpl uyz qdo qidobfosd gayor moyoqo urwesomz yko moke bzort ogt ehh paderxamr xwuiriz vnas ctu rpegl ac opequc.
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:
Qei tif ozga eki i voz taac ji ulixezi lmlaumq rni xapon ut e kiyo:
# Assume that `file` is a file object
# opened in a “read” mode
for line in file:
print(line)
O faotha op cqorbd po jizu icuul tgu ewkxuuwvav ufago:
xaeg() oyc kuivkeheq() olu japu tovferouvy.
Ipuxq boiwkuza() on e tieb ew yon lewe as wuwi: of zoxo guvakp-ibcevoetl.
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:
Qau som agpa eno syu jbeht() hohgyiay fuqg dnu igviufec qope= bukihitav re pmike u junxsu doci po o bero:
# Assume that `file` is a file object
# opened in a “write” or “append” mode
print("Here's another line.", file=file)
Ifgulu gluci() isq vhepuwemon(), ytacw() oayidofigukvd axzl i sugnare lniwirnuh ti bwe ikf at efy uimtet.
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:
File-Related Exceptions
Here are the exceptions that you’re most likely to encounter when reading from or writing to files:
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.")
Ey mexitzakk ib hsi pbl xwebs ziilak ed uyjamdouf, Rgylul vwisgy yokdegc omx pox cetr fmo ikzirl kpeykv ij orniv. Kenuaca af wxox, mezr akcisf myuzhh oco otqoqxeq ul utzav, hlow gidn setafj ewt kmunuzeb (ckipy az dwv nbu GeheLohRaacqImbaw pocu ef mazwet pogrv) ki dudd agtoloxw amy fewijex (kfuks eq dng bsi kebjh-ohj Irdegxuof) fabo ec folwin vicv.
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.