Opening & Closing Files

Why File Handling?

Programs often need to work with data that persists beyond the program's execution. Files allow you to:

  • Store data permanently on disk
  • Read configuration settings
  • Process large datasets
  • Generate reports and logs
  • Share data between programs

The open() Function

Python uses the built-in open() function to work with files. It returns a file object that you can use to read, write, or manipulate the file.

Basic Syntax
# Basic file opening file = open("filename.txt") # With mode specified file = open("filename.txt", "r") # Read mode (default) # Always close when done! file.close()

File Modes

The mode parameter determines how the file is opened:

Mode Description
"r" Read (default) - File must exist
"w" Write - Creates new file, overwrites if exists
"a" Append - Adds to end of file, creates if not exists
"r+" Read and Write - File must exist
"w+" Write and Read - Creates/overwrites file
"rb" / "wb" Binary mode (for images, executables, etc.)
Key Concept

Always close files when you're done! Unclosed files can lead to data loss, resource leaks, and locked files. Python's context managers (covered in Section 4) handle this automatically.

Important

Opening a file in write mode ("w") will erase all existing content! Use append mode ("a") if you want to add to existing files.

LAB 1 Opening Files with Different Modes

Practice opening a file and displaying information about it. The virtual file system has a file called "sample.txt" pre-loaded.

main.py
Output
Click "Run" to see output...
Hint: The file object has properties like .name, .mode, and .closed that give you information about the file's state.
✓ Excellent! You've learned how to open files and check their properties.

Reading Files

Reading Methods

Python provides several methods to read file content:

read() - Read All Content
# Read entire file as a single string file = open("sample.txt", "r") content = file.read() print(content) file.close() # Read only first n characters file = open("sample.txt", "r") partial = file.read(50) # First 50 characters file.close()

Reading Line by Line

For large files, reading line by line is more memory-efficient:

readline() and readlines()
# Read one line at a time file = open("sample.txt", "r") line1 = file.readline() # First line line2 = file.readline() # Second line file.close() # Read all lines into a list file = open("sample.txt", "r") lines = file.readlines() # Returns list of lines print(lines[0]) # First line file.close()

Iterating Over Files

The most Pythonic way to read files line by line is to iterate directly:

File Iteration
file = open("sample.txt", "r") for line in file: print(line, end="") # end="" avoids double newlines file.close()
Key Concept

Each line read includes the newline character (\n) at the end. Use strip() to remove whitespace including newlines: line.strip()

LAB 2 Reading File Content

Read the file "data.txt" and count the number of lines and total characters. The file contains multiple lines of text.

main.py
Output
Click "Run" to see output...
Hint: Use readlines() to get all lines as a list, then use len() to count them. For characters, loop through each line with strip() to remove newlines.
✓ Great job! You can now read files and analyze their contents.

Writing Files

Writing Methods

Python provides methods to write content to files:

write() - Write String
# Create/overwrite file with write() file = open("output.txt", "w") file.write("Hello, World!\n") file.write("This is line 2.\n") file.close() # write() returns the number of characters written file = open("output.txt", "w") chars_written = file.write("Hello") print(chars_written) # Output: 5 file.close()

Writing Multiple Lines

Use writelines() to write a list of strings:

writelines() - Write List
lines = [ "Line 1\n", "Line 2\n", "Line 3\n" ] file = open("output.txt", "w") file.writelines(lines) file.close() # Note: writelines() doesn't add newlines automatically!

Appending to Files

Use append mode to add content without erasing existing data:

Append Mode ("a")
# Append to existing file file = open("log.txt", "a") file.write("New log entry\n") file.close() # Each time you run this, a new line is added
Write Mode Warning

Opening a file in "w" mode will immediately erase all existing content, even before you write anything! Always double-check your file mode.

LAB 3 Creating and Writing Files

Create a file called "report.txt" and write a simple report with a title and three bullet points.

main.py
Output
Click "Run" to see output...
Hint: Use "w" mode to create/write. Remember to include \n at the end of lines for proper formatting.
✓ Excellent! You've created and written a formatted file.

Context Managers (with Statement)

The Problem with Manual Closing

What happens if an error occurs before close()?

Problematic Code
file = open("data.txt", "r") content = file.read() result = int(content) # What if content isn't a number? Error! file.close() # Never reached if error occurs!

If an error occurs, the file stays open, potentially causing resource leaks.

The Solution: with Statement

Python's with statement automatically handles file closing, even if errors occur:

Context Manager Syntax
with open("data.txt", "r") as file: content = file.read() print(content) # File is automatically closed here! # Even this works correctly: with open("data.txt", "r") as file: content = file.read() result = int(content) # Even if error occurs... # ...file is STILL closed properly!
Best Practice

Always use with statements for file operations. It's the Python standard and prevents resource leaks. The file is guaranteed to close when the indented block ends.

Working with Multiple Files

You can open multiple files in a single with statement:

Multiple Files
# Read from one file, write to another with open("input.txt", "r") as infile, \ open("output.txt", "w") as outfile: content = infile.read() outfile.write(content.upper()) # Both files automatically closed!
LAB 4 Using Context Managers

Rewrite file operations using the with statement. Read "data.txt" and create "uppercase.txt" with the content in uppercase.

main.py
Output
Click "Run" to see output...
Hint: The with statement syntax is: with open(filename, mode) as variable:. No need to call close() - it's automatic!
✓ Perfect! You're now using best practices for file handling.

File Operations & Patterns

Common File Patterns

Here are some useful patterns you'll use frequently when working with files:

Line-by-Line Processing
# Process each line (memory efficient for large files) with open("large_file.txt", "r") as file: for line_num, line in enumerate(file, 1): processed = line.strip().upper() print(f"Line {line_num}: {processed}")

Checking if File Exists

Use the os module to check file existence before operations:

os.path Functions
import os # Check if file exists if os.path.exists("data.txt"): print("File exists!") # Check if it's actually a file (not directory) if os.path.isfile("data.txt"): print("It's a file!") # Get file size size = os.path.getsize("data.txt") print(f"File size: {size} bytes")

File Position (seek and tell)

You can move around within a file using seek() and check position with tell():

File Position Control
with open("data.txt", "r") as file: print(file.read(10)) # Read first 10 chars print(file.tell()) # Position: 10 file.seek(0) # Go back to start print(file.read(5)) # Read first 5 chars again file.seek(0, 2) # Go to end of file print(f"File size: {file.tell()}")

Working with CSV-like Data

A common pattern is reading structured text files:

Parsing Delimited Data
# Parse a simple CSV-like file with open("users.txt", "r") as file: for line in file: parts = line.strip().split(",") name, email, age = parts print(f"{name} ({email}) - Age: {age}")
LAB 5 Advanced File Processing

Read "users.csv" (comma-separated data), filter users over age 25, and write them to "adults.txt".

main.py
Output
Click "Run" to see output...
Hint: Use split(",") to separate CSV fields. Convert age to int() for comparison. Build a list of adults, then write them all at once.
✓ Excellent! You've mastered file processing patterns.

Chapter Summary

What You've Learned

In this chapter, you mastered Python file handling:

  • Opening Files: open(filename, mode) with various modes (r, w, a, r+)
  • Reading: read(), readline(), readlines(), and iteration
  • Writing: write() and writelines()
  • Context Managers: The with statement for safe, automatic cleanup
  • File Operations: Position control, existence checks, data parsing

Quick Reference

File Handling Cheat Sheet
# The Python Way (Best Practice) with open("file.txt", "r") as f: content = f.read() # Read all line = f.readline() # Read one line lines = f.readlines() # Read all as list with open("file.txt", "w") as f: f.write("text") # Write string f.writelines(["a\n", "b\n"]) # Write list with open("file.txt", "a") as f: f.write("appended\n") # Add to end # File modes: r=read, w=write, a=append, r+=both, b=binary
Golden Rules

1. Always use with statements for file operations.
2. Use "w" mode carefully - it overwrites existing files!
3. Remember to add \n for newlines when writing.
4. Use strip() to remove trailing newlines when reading.

Chapter 7 Complete!

You've mastered Python file handling. Time to test your skills!