๐Ÿ‡ฌ๐Ÿ‡ง Limited Time โ€” UK Onlyยท๐ŸŽ“ Free Learning for 1 Monthยท๐Ÿค– Free AI Training Includedยท๐Ÿ“š 4,000+ Lessons ยท 35,000+ Quizzesยท๐Ÿ† GCSE Mocks ยท Olympiad Papersยทโšก Selected Students Only ยท Limited Placesยท๐ŸŽ Free Value Worth ยฃ2,000ยท๐Ÿ‡ฌ๐Ÿ‡ง Limited Time โ€” UK Onlyยท๐ŸŽ“ Free Learning for 1 Monthยท๐Ÿค– Free AI Training Includedยท๐Ÿ“š 4,000+ Lessons ยท 35,000+ Quizzesยท๐Ÿ† GCSE Mocks ยท Olympiad Papersยทโšก Selected Students Only ยท Limited Placesยท๐ŸŽ Free Value Worth ยฃ2,000ยท๐Ÿ‡ฌ๐Ÿ‡ง Limited Time โ€” UK Onlyยท๐ŸŽ“ Free Learning for 1 Monthยท๐Ÿค– Free AI Training Includedยท๐Ÿ“š 4,000+ Lessons ยท 35,000+ Quizzesยท๐Ÿ† GCSE Mocks ยท Olympiad Papersยทโšก Selected Students Only ยท Limited Placesยท๐ŸŽ Free Value Worth ยฃ2,000ยท
๐Ÿ Python

Reading and Writing Files

๐Ÿ“š What is File I/O? File I/O (Input/Output) lets your program read data from files and save results back to disk. Without files, every time you close the program all data is lost. With files, you can load saved games, read configuration, process datasets, and log events.

8 min 10 XP Lesson 13 of 21
Reading and Writing Files
๐ŸŒ

Appy Saysโ€ฆ

Every real app reads files โ€” config settings, user data, game saves, CSVs of scores. Python makes file reading beginner-friendly AND safe with the with statement. Learn this and your programs can talk to the filesystem.

๐Ÿ“–

What is File Reading in Python?

Python's built-in open() function opens a file and returns a file object. You then call methods on it to read the content. The with keyword automatically closes the file when you're done โ€” even if an error occurs.

  • โ€ขopen('file.txt', 'r') โ€” open for reading (default mode)
  • โ€ขopen('file.txt', 'w') โ€” open for writing (creates or overwrites)
  • โ€ขopen('file.txt', 'a') โ€” open for appending
  • โ€ข.read() โ€” returns entire file as one string
  • โ€ข.readlines() โ€” returns a list where each item is one line
  • โ€ข.readline() โ€” reads one line at a time
  • โ€ขUse with open(...) as f: โ€” always use this pattern
๐ŸŽฎ

Think of it like loading a Minecraft world

When you load a saved Minecraft world, the game opens the save file, reads all the block data, loads it into memory, then closes the file. Python's with open() does exactly this โ€” open the file, read it, close it automatically, with no data leaks.

โš™๏ธ

How It Works

  • โ€ข1. with open('scores.txt', 'r') as f: opens the file and assigns the file object to f
  • โ€ข2. Everything indented under with can use f
  • โ€ข3. content = f.read() reads the whole file into a string
  • โ€ข4. lines = f.readlines() reads into a list of strings, each ending in \n
  • โ€ข5. When the with block ends, Python automatically calls f.close()
  • โ€ข6. Writing: open with 'w' and call f.write('text')
๐ŸŒ

Real-World Examples

  • โ€ขA game app reads a high-scores .txt file to display the leaderboard
  • โ€ขSpotify's desktop app reads a local config file for audio settings on startup
  • โ€ขA school project reads a CSV of student names to generate personalised certificates
  • โ€ขA chatbot reads a responses.txt file to load its reply library without hardcoding
  • โ€ขYouTube's subtitle system reads .srt caption files line by line to sync with video
๐Ÿ’ก

Key Facts

  • โ€ขAlways use with open() โ€” it's called a context manager and guarantees the file is closed
  • โ€ขAdd encoding='utf-8' to handle emoji and non-ASCII characters: open('f.txt', 'r', encoding='utf-8')
  • โ€ขPython's csv module makes reading CSV files even easier than doing it manually
  • โ€ขLarge files should use a for line in f: loop โ€” this reads one line at a time without loading everything into RAM
โš ๏ธ

Watch Out!

Opening a file with 'w' mode immediately deletes all existing content โ€” even before you write anything new. If you want to add to an existing file, use 'a' (append) mode instead.

๐Ÿ“Œ

Remember

Always use with open('file.txt') as f: โ€” never f = open(...) without closing. The with block is the professional standard.

โœ…

What You Learned

  • โ€ขwith open('file.txt', 'r') as f: safely opens and auto-closes files
  • โ€ขUse .read() for full content, .readlines() for a line list, 'w' to write
  • โ€ขUnlocks: loading game saves, reading configs, processing data files, building file-based apps

Key Facts

  • โ†’Always use with open() โ€” it's called a context manager and guarantees the file is closed
  • โ†’Add encoding='utf-8' to handle emoji and non-ASCII characters: open('f.txt', 'r', encoding='utf-8')
  • โ†’Python's csv module makes reading CSV files even easier than doing it manually
  • โ†’Large files should use a for line in f: loop โ€” this reads one line at a time without loading everything into RAM

Real-World Examples

โ€ข A game app reads a high-scores <code>.txt</code> file to display the leaderboard โ€ข Spotify's desktop app reads a local config file for audio settings on startup โ€ข A school project reads a CSV of student names to generate personalised certificates โ€ข A chatbot reads a <code>responses.txt</code> file to load its reply library without hardcoding โ€ข YouTube's subtitle system reads <code>.srt</code> caption files line by line to sync with video

Remember

Always use with open('file.txt') as f: โ€” never f = open(...) without closing. The with block is the professional standard.

Quick Quiz

1 / 2

with open(...) as f: ensures?