Home Course Roadmap
Lesson 36 · Files & Data 45–55 minutes Beginner

Python File Handling

Learn how Python programs read, create, write, append, and manage files so your applications can work with persistent data beyond the lifetime of a program.

Files & Data
Reading progress: 0%
01

Learning Objectives

Until now, most of the data used by your Python programs existed only while the program was running. File handling allows your programs to store and retrieve information from files.

By the end of this lesson, you will be able to:
  • Understand what file handling means.
  • Open files using Python.
  • Understand common file modes.
  • Read complete files and individual lines.
  • Write new content to files.
  • Append content without replacing existing data.
  • Use the with statement safely.
  • Understand text and binary files.
  • Control file positions using seek().
  • Handle common file-related errors.
  • Work with files and folders in practical programs.
02

What Is File Handling?

File handling means using a program to create, read, modify, or manage files stored on a computer.

Files allow information to remain available even after your Python program stops running.

Think about persistence

A normal Python variable exists in memory while your program is running. A file can store information so that another program execution can read it later.

Example

Python
name = "Ali"

with open("student.txt", "w") as file:
    file.write(name)

This creates or replaces student.txt and stores the student's name inside it.

03

Why Files Matter

Files are useful whenever information needs to survive after the program finishes.

Examples include:

  • Saving customer information.
  • Storing application settings.
  • Saving reports.
  • Keeping logs.
  • Reading configuration data.
  • Importing datasets.
  • Exporting results.
  • Storing notes and text.
Simple data flow
Python Program
      ↓
   Write Data
      ↓
    File
      ↓
  Read Later
      ↓
Python Program
04

Common File Types

Python can work with many types of files.

.txt   → Text files
.csv   → Spreadsheet-style data
.json  → Structured data
.py    → Python source code
.log   → Log files
.jpg   → Image file
.png   → Image file
.pdf   → Document file

Different file formats require different techniques. In this lesson, we focus primarily on text file handling.

CSV and JSON files will be covered in more detail in later lessons.

05

The open() Function

Python provides the built-in open() function for working with files.

Basic syntax

Syntax
open(filename, mode)

For example:

Example
file = open("notes.txt", "r")

This opens notes.txt in read mode.

Important

When using open() directly, the file should eventually be closed. The safer and preferred approach for normal file operations is the with statement, which we will learn later in this lesson.

06

File Modes

The mode tells Python what you intend to do with the file.

"r"   Read
"w"   Write
"a"   Append
"x"   Create
"b"   Binary
"t"   Text

Read mode

"r" opens a file for reading.

Write mode

"w" opens a file for writing. If the file already exists, its previous contents are replaced.

Append mode

"a" adds new content to the end of an existing file.

Create mode

"x" creates a new file and raises an error if the file already exists.

Be careful with "w"

Write mode can overwrite existing file contents. Always choose the mode based on what you actually want the program to do.

07

Reading a File

The read() method reads file content.

notes.txt
Python is powerful.
Python is readable.
Python is versatile.
Python
with open("notes.txt", "r") as file:
    content = file.read()

print(content)
Output
Python is powerful.
Python is readable.
Python is versatile.

Without an argument, read() attempts to read the remaining contents of the file.

Reading a specific number of characters

Example
with open("notes.txt", "r") as file:
    content = file.read(6)

print(content)
Python
08

readline()

The readline() method reads one line at a time.

Example
with open("notes.txt", "r") as file:
    first_line = file.readline()

print(first_line)

You can call readline() repeatedly to read subsequent lines.

Multiple lines
with open("notes.txt", "r") as file:
    line1 = file.readline()
    line2 = file.readline()

print(line1)
print(line2)
09

readlines()

The readlines() method reads the lines and returns them as a list.

Example
with open("notes.txt", "r") as file:
    lines = file.readlines()

print(lines)
Example output
['Python is powerful.\n',
 'Python is readable.\n',
 'Python is versatile.']
Memory consideration

Reading a very large file with readlines() loads its lines into memory. For large files, processing one line at a time is often more efficient.

10

Looping Through a File

A file object can be iterated over directly.

Example
with open("students.txt", "r") as file:

    for line in file:
        print(line.strip())

This is a useful technique for processing files line by line without loading the entire file into memory.

Professional habit

For large text files, line-by-line processing is often a good balance between simplicity and memory efficiency.

11

Writing to a File

Use "w" mode and the write() method to write text to a file.

Example
with open("message.txt", "w") as file:
    file.write("Hello from PyLearn!")

If message.txt does not exist, Python creates it.

If it already exists, its previous content is replaced.

Writing multiple pieces of text

Example
with open("profile.txt", "w") as file:
    file.write("Name: Ali\n")
    file.write("Age: 25\n")
    file.write("City: Multan\n")
12

Appending to a File

Use "a" mode when you want to add information without deleting the existing content.

Example
with open("activity.log", "a") as file:
    file.write("User logged in\n")

If the file already contains:

User opened the application
User viewed dashboard

After appending, it may contain:

User opened the application
User viewed dashboard
User logged in
Common use

Append mode is especially useful for logs, activity records, notes, and event histories.

13

Writing Multiple Lines

The writelines() method can write multiple strings from an iterable.

Example
lines = [
    "Ali\n",
    "Sara\n",
    "Ahmed\n"
]

with open("students.txt", "w") as file:
    file.writelines(lines)
Important

writelines() does not automatically insert newline characters. If you want each item on a separate line, include \n yourself.

14

The with Statement

The with statement is the preferred way to handle ordinary Python file operations.

Recommended approach
with open("notes.txt", "r") as file:
    content = file.read()

print(content)

When the with block finishes, Python handles closing the file automatically, including when an exception occurs during the block.

Manual approach

Possible, but less convenient
file = open("notes.txt", "r")

content = file.read()

file.close()
Best practice

Prefer with open(...) for normal file operations. It makes resource management safer and cleaner.

15

File Encoding

Text files store characters using an encoding. When working with text, explicitly specifying an encoding such as UTF-8 is often a good practice.

Example
with open(
    "message.txt",
    "w",
    encoding="utf-8"
) as file:

    file.write("Hello Python! مرحبا")

You can also specify encoding when reading:

Reading UTF-8
with open(
    "message.txt",
    "r",
    encoding="utf-8"
) as file:

    content = file.read()
Why encoding matters

Explicit encoding helps your application handle text consistently across different systems and languages.

16

Binary Files

Not every file contains ordinary text. Images, audio, videos, and many other formats contain binary data.

Python supports binary modes using b.

Reading binary data

Example
with open("photo.jpg", "rb") as file:
    data = file.read()

Writing binary data

Example
with open("copy.jpg", "wb") as file:
    file.write(data)
Text vs binary

Use text mode for textual data and binary mode for binary content such as images and other non-text files.

17

File Position & seek()

When you read from a file, Python maintains a current position within that file.

The seek() method moves that position.

Example
with open("notes.txt", "r") as file:

    print(file.read(6))

    file.seek(0)

    print(file.read(6))
Output
Python
Python

seek(0) moves the file position back to the beginning.

18

tell()

The tell() method returns the current file position.

Example
with open("notes.txt", "r") as file:

    print(file.tell())

    file.read(6)

    print(file.tell())
Example output
0
6

The exact position can depend on the file and how it is opened, but the key idea is that tell() reports the current position and seek() changes it.

19

Common File Errors

FileNotFoundError

Reading a file that does not exist can raise FileNotFoundError.

Example
with open("missing.txt", "r") as file:
    content = file.read()

PermissionError

Python may raise PermissionError when the operating system does not allow the requested operation.

IsADirectoryError

Attempting to open a directory as though it were a normal file can raise IsADirectoryError.

Handling file errors

Later, when you learn exception handling, you will be able to use try and except to handle expected file errors gracefully.

20

Working with Files & Folders

Python's os and pathlib modules provide tools for working with files and directories.

Using pathlib

pathlib provides an object-oriented approach to filesystem paths.

Example
from pathlib import Path

file_path = Path("notes.txt")

print(file_path.exists())

Creating a directory

Example
from pathlib import Path

folder = Path("reports")

folder.mkdir(exist_ok=True)

Reading and writing with pathlib

Example
from pathlib import Path

file = Path("report.txt")

file.write_text(
    "Monthly sales report",
    encoding="utf-8"
)

content = file.read_text(
    encoding="utf-8"
)

print(content)
Modern Python

pathlib is often a clean and readable choice for filesystem paths. You will encounter it frequently in modern Python projects.

21

Real-World Examples

File handling becomes useful in many practical applications.

Example 1 — Application Log

logger.py
message = "User opened the dashboard\n"

with open("app.log", "a", encoding="utf-8") as file:
    file.write(message)

Example 2 — Student Records

students.txt
Ali,85
Sara,92
Ahmed,78

A Python program can read these records and process them.

Example 3 — Saving a Report

report.py
report = """Sales Report
-------------
Total Orders: 125
Revenue: 450000
Top Product: Laptop
"""

with open("sales_report.txt", "w", encoding="utf-8") as file:
    file.write(report)

Example 4 — Simple Notes Application

notes.py
note = input("Enter a note: ")

with open("notes.txt", "a", encoding="utf-8") as file:
    file.write(note + "\n")

print("Note saved successfully.")

This small program demonstrates a real persistence workflow: user input → file storage → future retrieval.

22

Common Mistakes

1. Using "w" when you meant "a"

Write mode replaces existing contents. Use append mode when you need to preserve existing data.

2. Forgetting the newline

write() does not automatically add a new line. Use \n when appropriate.

3. Forgetting encoding

For text applications, explicitly using encoding="utf-8" can make behavior more predictable across systems.

4. Reading a missing file

Make sure the path is correct and handle expected missing-file situations appropriately.

5. Not using with

The with statement makes file resource management safer and cleaner.

6. Using text mode for binary files

Images and other binary data should be handled using binary modes such as rb and wb.

Professional habit:

Be deliberate about the file mode, path, encoding, and whether your program should replace, append, or simply read existing information.

23

Practice Exercises

Complete these exercises without copying the examples directly. Try to build each solution yourself.

Exercise 1 — Create a File

Create a file called welcome.txt and write a welcome message inside it.

Exercise 2 — Read a File

Read welcome.txt and display its contents.

Exercise 3 — Student Names

Store five student names in a text file, one name per line, and then read them using a loop.

Exercise 4 — Append Notes

Ask the user for a note and append it to notes.txt.

Exercise 5 — Word Counter

Read a text file and calculate the total number of words.

Exercise 6 — Line Counter

Read a file line by line and count how many lines it contains.

Exercise 7 — File Copy

Read a text file and create another file containing the same content.

Exercise 8 — pathlib

Use pathlib.Path to check whether a file exists and display its file name.

24

Mini Challenge — Student Record Manager

Build a small command-line application that stores student records inside a text file.

Your mission:

Create a program that allows a user to add student records and view the saved records later.

Suggested file

students.txt

Each record could contain

Name: Ali
Age: 20
Marks: 85
----------------
Name: Sara
Age: 21
Marks: 92
----------------

Requirements

  1. Ask the user for a student's name.
  2. Ask for age.
  3. Ask for marks.
  4. Save the record to students.txt.
  5. Use append mode so existing students are preserved.
  6. Add an option to display all saved students.
  7. Use the with statement for file operations.

Bonus challenge

Add a search option that asks for a student's name and displays matching records from the file.

What you are practicing:

User input + strings + loops + conditions + file reading + file writing + file persistence.

25

Quick Knowledge Check

Test what you learned about Python file handling.

1. Which function is used to open a file?

2. Which mode is used for reading?

3. What does "w" mode do if the file already exists?

4. Which mode is normally used to append content?

5. Which method reads the entire remaining file content?

6. What is the main advantage of using with open()?

7. Which mode is appropriate for reading binary data?

8. What does seek(0) generally do?

9. Which method reports the current file position?

10. Which error can occur when a requested file does not exist?

26

Lesson Summary

File handling allows Python programs to store and retrieve information outside the program's temporary memory.

Key concepts from this lesson:
  • open() is used to open files.
  • "r" is used for reading.
  • "w" is used for writing and can replace existing content.
  • "a" is used for appending.
  • "x" creates a new file and fails if it already exists.
  • read() reads file content.
  • readline() reads one line.
  • readlines() returns lines as a list.
  • Files can be processed line by line using loops.
  • write() writes text to a file.
  • writelines() writes multiple strings.
  • with open() is the preferred approach for ordinary file operations.
  • UTF-8 is a common text encoding.
  • Binary files use modes such as rb and wb.
  • seek() changes the file position.
  • tell() reports the current position.
  • pathlib provides modern tools for filesystem paths.

You have now learned how Python programs can persist data using files. This is a major step toward building programs that work with real-world information.

In the next lesson, we will work with one of the most important data formats used by modern applications: JSON.

Ready for the Next Lesson?

Make sure you understand reading, writing, appending, file modes, with, encoding, and basic filesystem operations before continuing.