CodingNic

Files, Errors, and Automation

Reading Text Files

Files, Errors, and Automation 24 min read

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.txt
  • names.txt
  • report.txt

Why Reading Files Matters

Reading files helps programs:

  • Load saved data
  • Show reports
  • Read settings
  • Reuse information later

Opening a File

Use open().

python
file = open("notes.txt")

This opens the file.

Reading All Content

Use read().

python
file = open("notes.txt")
content = file.read()

print(content)

Example File Content

If notes.txt contains:

text
Learn Python
Practice daily

Output

text
Learn Python
Practice daily

Closing the File

After using a file, close it.

python
file.close()

This frees system resources.

Better Way: with open()

A safer way is using with open().

Python closes the file automatically.

python
with open("notes.txt") as file:
    content = file.read()
    print(content)

Output

text
Learn Python
Practice daily

Reading One Line

Use readline().

python
with open("notes.txt") as file:
    line = file.readline()
    print(line)

Output

text
Learn Python

Reading All Lines as a List

Use readlines().

python
with open("notes.txt") as file:
    lines = file.readlines()
    print(lines)

Output

text
['Learn Python\n', 'Practice daily']

Loop Through Lines

python
with open("notes.txt") as file:
    for line in file:
        print(line.strip())

Output

text
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:

text
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:
text
Study
Code
Repeat
  • Read the file
  • Print each line using a loop

Expected output:

text
Study
Code
Repeat

Real World Use Case

Programs read saved notes, user settings, logs, reports, and data files every day.

Quiz

  1. What does open() do?
  2. What does read() return?
  3. Why is with open() better?
  4. 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.