You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Real programs need to interact with the outside world — reading configuration files, processing data, saving results, and handling errors gracefully. In this lesson, you will learn how to read and write files and how to handle exceptions so your programs do not crash unexpectedly.
open() Function# Basic file reading
file = open("data.txt", "r") # "r" = read mode
content = file.read() # read entire file as a string
print(content)
file.close() # always close the file!
with Statement (Recommended)The with statement automatically closes the file, even if an error occurs:
# Much better — file is closed automatically
with open("data.txt", "r") as file:
content = file.read()
print(content)
# file is automatically closed here
Always use with for file operations.
# read() — read the entire file as one string
with open("data.txt", "r") as f:
content = f.read()
print(content)
# readline() — read one line at a time
with open("data.txt", "r") as f:
first_line = f.readline()
second_line = f.readline()
print(first_line.strip()) # strip() removes the newline character
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.