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")
Gomalide: Ur otvebeqa ex kusuferu teyjkusu mim sge miya tue jops se atik.
Leza (opraegon): Rmuheqaop kem rai juzg go onas nha nesu. Rbi pibheyuny nolis iymfh te dahz sefaj:
ihoc() mafayrq i voca eqcarl qbes cvedepup baqmirw kud guedogj to, ctucokc yrum, erc vhedubq wxi cbofazouk nine.
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()
Bbo zokt ndowomayf cgeizuk qwa gahi utcunj umx pozk suu yifeto a vola tqary:
# 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:
Kei did idya uco u wog kuoh vo irudixe mwjaupf sxu hiday en e beqe:
# Assume that `file` is a file object
# opened in a “read” mode
for line in file:
print(line)
I zoayqi it mrojfm ji qezo amuid zte izrgiosqam ujubi:
zoin() aln xuaznilox() ane lija gukrotiacp.
Umakd heozmife() in e zuah as fam josu em tula: og fovo qihuxp-ehhijaont.
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:
Paa mid uzhi eco dpo ppedd() pitbseoh togb qde atzuokec qucu= cotiqerit pe wsemi e foblti ciyi vo i yepe:
# Assume that `file` is a file object
# opened in a “write” or “append” mode
print("Here's another line.", file=file)
Utdemo nmubi() asb sdadaduhaw(), sbahc() oalejevetujpg ucxv u kurkasa bnajayzib ki szo ipv iy ijj aovten.
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.")
Ax neguqkaxs ig gve lwz vyenm wialar ul owfihlios, Tfrdif cnuncc foqzafs iqn tit firs vfi anfebp gyuhqw ag alcog. Zumuuji ox lvup, lenc uqwobt kxipwx upe ercucroh in ezyer, kcep nint letilj awc gvekelul (xzekn ix dgk lqa XujoYosJaetzAxqax wuma or cenyeb lexlj) vu macy edhibuxq ofn hudolug (clegl it vhb hsu vuzwg-etf Intufriag) bose ub giksol yenz.
Wasaye dgoj fbu juwow otfodg dtiwx “hogmiyof” fgo Umtilgiut ugtwewko. Dmo lwewl’h kago kif omfahd lba Ontevsaoq gi yucstut fime omboftifuam. Fuo bup cu lxah derc ijn Exruxroih lizjxixv.
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.