ICT582 Python Revision
🎯 Learning Objectives
πŸ“š Key Concepts

Opening Files β€” open()

ModeMeaning
'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

MethodWhat it doesExample
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 stringlen("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
  1. Know file modes: 'r' read, 'w' write (overwrites!), 'a' append.
  2. The with statement automatically closes the file β€” always preferred.
  3. Strings are immutable β€” s.upper() returns a new string, it doesn't change s.
  4. Know split() and join(): "a b c".split() β†’ ['a','b','c']; " ".join(['a','b','c']) β†’ "a b c".
  5. f-string formatting: f"{value:.2f}" for 2 decimal places.
❌ Common Mistakes
⚑ Quick Recap
← Topic 06: Functions Topic 08: Exceptions β†’