Files store data persistently. Variables in memory disappear when a program ends, but data written to a file can remain. File I/O means input from files and output to files.
💾 File Persistent text ⇄ 🐍 Python program Read input, process it, and write results
open() and file modes
open() returns a file object. Reading, writing, and closing happen through that object.
file = open("text.txt", "r", encoding="UTF-8")
content = file.read()
file.close()| Mode | Meaning |
|---|---|
r | Read only; file must exist |
w | Write; overwrite existing content |
a | Append at the end |
r+ | Read and write; file must exist |
Prefer with open(...) as file, which closes the file automatically after the block. Explicit encoding="UTF-8" also avoids mismatched system defaults.
with open("text.txt", "r", encoding="UTF-8") as file:
content = file.read()KNOWLEDGE QUIZ
QUESTION
What is the main benefit of with open(...) as file?
Reading methods
read(): read everything into one string.readline(): read one line.readlines(): return all lines as a list of strings.- Iterate over the file object to process one line at a time, useful for larger files.
KNOWLEDGE QUIZ
QUESTION
What does readlines() normally return?
Parsing words
The following program reads quotes.txt, strips English punctuation, and writes every word to words.txt. The two files may share one with statement or use nested with blocks.
import string
with open("words.txt", "w", encoding="UTF-8") as output_file:
with open("quotes.txt", "r", encoding="UTF-8") as input_file:
for line in input_file:
for word in line.split():
word = word.strip(string.punctuation)
output_file.write(word + "\n")KNOWLEDGE QUIZ
QUESTION
Which statement writes word followed by a newline?
HANDS-ON PRACTICE
Write and read a study log
- Create study_log.txt in w mode.
- Write three notes: “Learned open”, “Understood with”, and “Can read line by line”.
- Open it again in r mode.
- Use enumerate(..., start=1) to print “1: content”.
HANDS-ON PRACTICE
Split quotes into a word file
- First create quotes.txt with two English quotes.
- Read each line and split it into words.
- Strip characters from string.punctuation.
- Write each non-empty word to its own line in words.txt.