Topic 07 of 12 | π Lecture 7 β ICT582Topic07.pdf
Files & String Processing
Read and write files, use string methods, and format output with f-strings.
π― Learning Objectives
- Open, read, write, and close files using
open() - Use the
withstatement to safely handle files - Use common string methods:
upper(),lower(),strip(),split(),join(),replace() - Format strings using f-strings and
.format() - Read files line by line and process text data
π Key Concepts
Opening Files β open()
| Mode | Meaning |
|---|---|
'r' | Read (default). File must exist. |
'w' | Write. Creates new file or overwrites existing. |
'a' | Append. Adds to end of file. Creates if not exists. |
'r+' | Read and write. |
f = open("data.txt", "r") # open for reading
content = f.read() # read all as one string
f.close() # always close!
The with Statement (Recommended)
Automatically closes the file when the block ends β even if an error occurs. Always use with.
# Reading a file
with open("data.txt", "r") as f:
content = f.read()
# file is automatically closed here
print(content)
Reading Files
# Read entire file as string
with open("data.txt") as f:
text = f.read()
# Read one line at a time
with open("data.txt") as f:
line = f.readline() # reads one line (includes \n)
# Read all lines into a list
with open("data.txt") as f:
lines = f.readlines() # list of strings with \n
# Iterate line by line (most efficient)
with open("data.txt") as f:
for line in f:
print(line.strip()) # strip() removes \n
Writing Files
# Write (overwrites if file exists)
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# Append (adds to existing file)
with open("output.txt", "a") as f:
f.write("Appended line\n")
Note: write() does not add newlines automatically β you must add \n.
String Methods
| Method | What it does | Example |
|---|---|---|
s.upper() | All uppercase | "hello".upper() β "HELLO" |
s.lower() | All lowercase | "HELLO".lower() β "hello" |
s.strip() | Remove leading/trailing whitespace | " hi ".strip() β "hi" |
s.split(sep) | Split into list by separator | "a,b,c".split(",") β ['a','b','c'] |
sep.join(list) | Join list into string | ",".join(['a','b']) β "a,b" |
s.replace(old, new) | Replace occurrences | "abba".replace("b","x") β "axxa" |
s.find(sub) | Index of first occurrence (-1 if not found) | "hello".find("ll") β 2 |
s.startswith(pre) | Check if starts with prefix | "hello".startswith("he") β True |
s.endswith(suf) | Check if ends with suffix | "file.py".endswith(".py") β True |
len(s) | Length of string | len("hello") β 5 |
String Formatting β f-strings (Recommended)
f-strings (formatted string literals) are the modern way to embed variables in strings.
name = "Alice"
score = 85.5
# f-string (Python 3.6+)
print(f"Name: {name}, Score: {score}")
# Output: Name: Alice, Score: 85.5
# Format numbers
print(f"Score: {score:.2f}") # 2 decimal places: 85.50
print(f"Pi: {3.14159:.3f}") # Pi: 3.142
# Expressions inside
print(f"Double: {score * 2}") # Double: 171.0
String Indexing and Immutability
Strings are sequences β you can index and slice them like lists. But strings are immutable β you cannot change individual characters.
s = "Python"
print(s[0]) # P
print(s[-1]) # n
print(s[2:5]) # tho
print(s[::-1]) # nohtyP (reversed)
s[0] = "J" # TypeError! Strings are immutable
π» Code Examples
Example 1 β Count words in a file
with open("story.txt", "r") as f:
text = f.read()
words = text.split()
print(f"Word count: {len(words)}")
Example 2 β CSV-style file reading
# students.txt content: "Alice,85\nBob,72\n"
with open("students.txt") as f:
for line in f:
name, score = line.strip().split(",")
print(f"{name}: {score}")
Example 3 β String processing
sentence = " The Quick Brown Fox "
clean = sentence.strip().lower()
words = clean.split()
print(words) # ['the', 'quick', 'brown', 'fox']
print(len(words)) # 4
print(" ".join(words)) # the quick brown fox
β οΈ Exam Focus
- Know file modes:
'r'read,'w'write (overwrites!),'a'append. - The
withstatement automatically closes the file β always preferred. - Strings are immutable β
s.upper()returns a new string, it doesn't changes. - Know
split()andjoin():"a b c".split()β['a','b','c'];" ".join(['a','b','c'])β"a b c". - f-string formatting:
f"{value:.2f}"for 2 decimal places.
β Common Mistakes
- Opening with
'w'when you want to append β'w'erases existing content! - Forgetting
f.close()β usewithto avoid this. - Not stripping
\nfrom lines βline.strip()removes newline and spaces. - Trying to reassign string characters:
s[0] = 'x'is aTypeError.
β‘ Quick Recap
open(file, mode):'r'read,'w'write/overwrite,'a'append.- Always use
with open(...) as f:β auto-closes the file. - Read:
f.read(),f.readline(),f.readlines(), or iterate withfor line in f. - String methods return new strings β strings are immutable.
- f-strings:
f"Hello {name}"β cleaner than concatenation. - Key methods:
strip(),split(),join(),replace(),upper(),lower().