Python Files Foundation
open() / read() / write() Topic 08 Foundation

Files — reading and writing to disk

Foundation lesson for file operations in Python. Learn to open files, read data, write data, and close files properly.

Picture this: disk ↔ program

open() borrows the file. read/write. close() (or with) gives it back.

disk filenotes.txt
→
open / withborrow
→
read or writeyour code
→
closesave & release

with open(...) as f: closes even if something goes wrong.

In easy words: What are files?

A file is data stored on disk that survives after your program ends. Unlike variables which disappear, files stay on your computer. Python can read from files (input) and write to files (output).

Diagram — open → read/write → close

open() read / write close / with

Where files are used

Files are used to store logs, save game progress, read configuration, store user data, analyze large text documents, process CSV data, and persist any information that needs to last beyond program execution.

File modes

  • "r" — read (default). File must exist.
  • "w" — write. Creates file or erases existing content.
  • "a" — append. Adds to end of file.
  • "r+" — read and write without erasing.

Three main steps

  • Open: file = open("name.txt", "r")
  • Read/Write: use file methods like read(), write(), readline()
  • Close: file.close() or use with

Real world: student grades file

Your school stores grades in a text file: one line per student "Alice: 95". Your program reads the file line-by-line, processes the data, and writes results to a new file. Without files, all data is lost when the program ends.

File modes explained
📖 "r" — Read Opens existing file
Read content only
Will error if file not found
Default mode
✏️ "w" — Write Creates new file or overwrites
Erases old content!
Can write new data
Useful for fresh output
📝 "a" — Append Adds to end of file
Preserves old content
Good for logs
Never erases
🔄 "r+" — Read+Write Opens existing file
Can read and modify
Doesn't erase
Advanced use
Step-by-step file reading

Reading a file

1. Open the file
file = open("data.txt", "r")
2. Read content
content = file.read() # entire file as string
Or use readlines() for list of lines, or readline() for one line at a time.
3. Close the file
file.close() # important!
Step-by-step file writing

Writing to a file

1. Open for writing
file = open("output.txt", "w")
Mode "w" creates the file if it doesn't exist. If it does, old content is erased.
2. Write content
file.write("Hello, File!")
Add \n for newlines: file.write("Line 1\n")
3. Close the file
file.close() # saves to disk

File methods reference

1file.read() # entire file as one string
2file.readline() # one line (with \n)
3file.readlines() # list of all lines
4for line in file: # loop each line
5file.write("text") # write string
6file.close() # save and close
The "with" statement (safer)

Best practice: auto-close

1with open("data.txt", "r") as file:
2content = file.read()
3print(content)
4# file auto-closes here
Benefit: file closes automatically even if an error occurs. No need to remember close().

Example Program

1# Read from input.txt and write to output.txt
2with open("input.txt", "r") as infile:
3lines = infile.readlines()
4with open("output.txt", "w") as outfile:
5outfile.write(f"Total lines: {len(lines)}\n")
6outfile.writelines(lines)

File Handling — Topic Quiz

Check understanding

Answer all questions, then click Check answers. Use this before Practice in the editor.

Q1. Safest everyday pattern to open files?

Q2. Mode 'r' means…

Q3. Mode 'a' is for…

Q4. Why close files?

Score: —