Python Programming and File Handling
What this domain tests
Core Python programming plus persistent data: syntax, control flow, functions, strings, lists, tuples, dictionaries, exceptions, and reading or writing text files with the correct modes.
Core rules
- Indentation defines blocks. A colon ends if, for, while, def and class headers.
- range(start, stop, step) excludes stop, so for i in range(1,5) gives 1, 2, 3, 4.
- Strings are immutable; lists are mutable; tuples are immutable; dictionaries store key–value pairs and are accessed by key.
- File modes: 'r' reads (default, error if the file is missing), 'w' writes (creates or truncates), 'a' appends, 'x' creates, 'r+' reads and writes. Add 'b' for binary.
- with open('data.txt','r') as f: closes the file automatically, even on error.
- read() returns the whole file as one string, readline() one line, readlines() a list of lines. Each line keeps its trailing newline - use .strip().
Worked example
with open('marks.txt','r') as f: total = 0 for line in f: total += int(line.strip()) print(total) The loop iterates over lines; strip removes the newline; int converts each mark; the sum is printed. If the file contained 40, 55 and 60 on separate lines, the output is 155.
Traps that cost marks
Opening with 'w' when you meant 'a', which erases the file; reading twice without seek(0) and getting an empty string; forgetting int() because file text and input() are strings; assuming write() adds a newline when it does not; using a mutable default argument.