Learning

Text File Handling

Text File Handling

Opening Files

python
# Modes: # 'r' - Read (default, error if doesn't exist) # 'w' - Write (creates new or TRUNCATES existing) # 'a' - Append (creates new or adds to end) # 'r+' - Read and write (doesn't truncate) # 'x' - Exclusive creation (error if file exists) # ALWAYS use 'with' statement! with open('data.txt', 'r') as f: content = f.read() # File is automatically closed here, even if error occurs # ❌ BAD (manual close, risky) f = open('data.txt') content = f.read() f.close() # What if read() crashes? File stays open!

Reading Files

python
with open('data.txt', 'r') as f: # Read entire file as string content = f.read() # Read N characters # first_10 = f.read(10) with open('data.txt', 'r') as f: # Read line by line (memory efficient for large files) for line in f: print(line.strip()) # .strip() removes \n with open('data.txt', 'r') as f: # Read all lines into list (includes \n at end of each!) lines = f.readlines() # ['line1\n', 'line2\n'] with open('data.txt', 'r') as f: # Read single line first_line = f.readline()

Writing Files

python
# Write (OVERWRITES existing content!) with open('output.txt', 'w') as f: f.write('Hello\n') f.write('World\n') # Write multiple lines (adds \n automatically) f.writelines(['Line 1\n', 'Line 2\n', 'Line 3\n']) # Append (adds to end, keeps existing content) with open('output.txt', 'a') as f: f.write('Appended line\n')

File Cursor Management

python
with open('data.txt', 'r') as f: print(f.tell()) # 0 (current position) first_5 = f.read(5) print(f.tell()) # 5 f.seek(0) # Go back to start content = f.read() # Reads from start again

Common Patterns

python
# Read file into list of clean lines def read_lines(filepath): with open(filepath, 'r') as f: return [line.strip() for line in f] # Safe write with error handling import os def safe_write(filepath, content): try: with open(filepath, 'w') as f: f.write(content) return True except IOError as e: print(f'Error: {e}') return False # Check if file exists before reading if os.path.exists('data.txt'): with open('data.txt') as f: data = f.read()
Key Rules
  • •ALWAYS use the 'with' statement to open files — it guarantees the file closes automatically
  • •'w' mode OVERWRITES the entire file — if you want to keep existing content, use 'a' (append)
  • •readlines() includes the newline character (\n) at the end of each string — use .strip() to remove it
  • •Iterating over a file object (`for line in f:`) is the most memory-efficient way to read large files
  • •seek(0) resets the cursor to the beginning, tell() returns the current cursor position
Your Task

Create a function `word_count(filepath)` that reads a text file and returns a dictionary of word frequencies (case-insensitive, ignore punctuation). Create a function `write_report(filepath, data_dict)` that writes a formatted report to a file where each line is `"Key: Value"` sorted by key name. Use `with` statements for all file operations.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define word_count function
Should use with open for reading
Should define write_report function
Should use with open for writing
Should sort keys in report
Should use f.write() to output