Reading Text Files
Reading Text Files
Many programs need to read saved information.
Examples:
- Notes
- Names
- Reports
- Settings
- Logs
Python can open a file and read its contents.
What Is a Text File?
A text file is a file that stores plain text.
Common examples:
notes.txtnames.txtreport.txt
Why Reading Files Matters
Reading files helps programs:
- Load saved data
- Show reports
- Read settings
- Reuse information later
Opening a File
Use open().
file = open("notes.txt")
This opens the file.
Reading All Content
Use read().
file = open("notes.txt")
content = file.read()
print(content)
Example File Content
If notes.txt contains:
Learn Python
Practice daily
Output
Learn Python
Practice daily
Closing the File
After using a file, close it.
file.close()
This frees system resources.
Better Way: with open()
A safer way is using with open().
Python closes the file automatically.
with open("notes.txt") as file:
content = file.read()
print(content)
Output
Learn Python
Practice daily
Reading One Line
Use readline().
with open("notes.txt") as file:
line = file.readline()
print(line)
Output
Learn Python
Reading All Lines as a List
Use readlines().
with open("notes.txt") as file:
lines = file.readlines()
print(lines)
Output
['Learn Python\n', 'Practice daily']
Loop Through Lines
with open("notes.txt") as file:
for line in file:
print(line.strip())
Output
Learn Python
Practice daily
strip() removes extra spaces and line breaks.
Common Beginner Errors
File Not Found
If the file does not exist, Python gives an error.
Wrong File Name
Check spelling carefully.
Forgetting to Close
Use with open() to avoid this problem.
Code Along
Create a file named hello.txt with:
Welcome
To Python Files
Then read and print it.
Mini Challenge
Build a notes reader.
Steps:
- Create a file named
tasks.txt - Add these lines:
Study
Code
Repeat
- Read the file
- Print each line using a loop
Expected output:
Study
Code
Repeat
Real World Use Case
Programs read saved notes, user settings, logs, reports, and data files every day.
Quiz
- What does
open()do? - What does
read()return? - Why is
with open()better? - What does
readline()do?
Assignment
Create a file called about.txt with 3 lines about yourself. Read and print all lines.
Summary
You learned how to open files, read text, read lines, loop through file content, and safely close files in Python.