Back to Blog

File Handling (read, write, append, context manager, pathlib) - Python Tutorial for Beginners #15

Sandy LaneSandy Lane

Video: File Handling (read, write, append, context manager, pathlib) - Python Tutorial for Beginners #15 by Taught by Celeste AI - AI Coding Coach

Watch full page →

File Handling in Python: Reading, Writing, Appending, Context Managers, and Pathlib

Mastering file handling is essential for many Python applications, from data processing to logging. This tutorial covers how to open files in different modes, read and write content, append data, use context managers for safe file operations, and leverage the modern pathlib module for file manipulation.

Code

# Writing to a file using 'write' mode (overwrites existing content)
with open("hello.txt", "w") as f:
  f.write("Hello, World!\n")  # Write a line to the file

# Reading the entire file content
with open("hello.txt", "r") as f:
  content = f.read()  # Read full content as a string
  print(content)

# Reading file lines into a list
with open("hello.txt", "r") as f:
  lines = f.readlines()  # Each line is an element in the list
  print(lines)

# Appending a new line to the file without overwriting
with open("hello.txt", "a") as f:
  f.write("New line!\n")  # Add a line at the end

# Using pathlib for modern file handling
from pathlib import Path

# Read text from a file easily
file_path = Path("hello.txt")
text = file_path.read_text()
print(text)

# Write text to a file
file_path.write_text("Overwritten content with pathlib\n")

# Append text by opening in append mode
with file_path.open("a") as f:
  f.write("Appended line using pathlib\n")

Key Points

  • The open() function is used to open files with modes: 'r' (read), 'w' (write), and 'a' (append).
  • Using the with statement ensures files are properly closed after operations, even if errors occur.
  • read() reads the entire file as a string, while readlines() returns a list of lines.
  • Appending mode ('a') adds content to the end of the file without deleting existing data.
  • Pathlib offers a modern, object-oriented approach to file handling, simplifying reading and writing files.