Before you can read from a file, you need to 'open' it. Python has a built-in function open()
for this.
The most common way to open a file for reading is: open('filename.txt', 'r')
. The 'r'
stands for 'read mode'.
Crucially: Files should always be closed after use to free up resources. The best practice in Python is to use the `with` statement, which handles closing automatically, even if errors occur:
with
open
('my_data.txt'
,'r'
)as
file_object
:# Code to read from file_object goes here
# File is automatically closed outside the 'with' block
The with
statement ensures our interaction with the file is safe and efficient.