Top Banner Ad

BCC302 — Unit 4: Python File Operations

Table of Contents (17 sections)

BCC302 · Python Programming · Unit 4

Python File Operations

Unit Scope & Exam Weightage: This unit covers persistent data: opening files in different modes, read(), readline() and readlines(), write() and writelines(), the with statement and file-pointer manipulation with seek()/tell(). The supplied question set has 18 recorded clusters; almost every 7-mark question is a file-processing program, so a working code pattern is more valuable than prose.


Front Page: Importance-Wise Topic Roadmap (2023–26 PYQs)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Reading files; Understanding read functions: read(); readline(); readlines() 8 (2023-24 ×4, 2024-25 ×3, 2025-26) 2m + 7m ×7 Survival Mode
2 write() and writelines() Manipulating file pointer using seek 6 (2024-25, 2025-26 ×5) 2m + 7m ×5 Program Bank
3 Writing files in python 4 (2023-24 ×2, 2024-25, 2025-26) 7m ×4 Modes & Writing
4 using file operations 1 (2025-26) 7m Theory + Code

2-Hour Last-Night Survival Checklist:

  1. Modes (Priority 3): r read (file must exist), w write (creates/overwrites), a append, x exclusive create; t text (default), b binary; + adds reading and writing.
  2. Read trio (Priority 1): read() → whole remaining file as one string; readline() → one line (returns '' at EOF); readlines() → list of lines.
  3. Write duo (Priority 2): write(str) → count of characters written; writelines(list) → writes each item, no automatic newlines.
  4. Pointer (Priority 2): seek(offset, whence) with whence 0=start, 1=current, 2=end; tell() gives current byte/character position.
  5. Five ready programs: reverse with commas, count lines/words/characters, digit-only words, last n lines, copy file.

1. File Handling Basics and Modes

File: A named block of persistent storage used by a program to read data from or write data to disk. Python treats a file as a stream, opened with open(filename, mode, encoding), which returns a file object with methods for reading, writing and positioning.

f = open("notes.txt", "r", encoding="utf-8")
data = f.read()
f.close()

1.1 File Mode Table (Memorise)

Mode Meaning Creates file? Initial pointer Truncates existing?
r Read only (text) No Start No
w Write only (text) Yes Start Yes
a Append (text) Yes End No
x Exclusive create Yes (fails if exists) Start No
r+ Read and write No Start No
w+ Read and write Yes Start Yes
a+ Read and write Yes End No
rb, wb, ab Binary versions as above as above as above

Python Examiner Tip: Never open a file in w mode when you only want to append — w silently erases the previous contents. This distinction frequently decides marks in "which mode" questions.

1.2 The with Statement (2-Mark Question)

with open("notes.txt", "r", encoding="utf-8") as f:
    data = f.read()
# file is closed automatically, even if an exception occurs

Purpose: the context manager calls f.close() automatically at the end of the block, preventing resource leaks and locked files. It is the recommended style in exam programs.

After-Topic PYQs:

  • 2024-25 (Sec A, 2 Marks): "Describe the purpose of the 'with' statement in file handling."
  • 2024-25 (Sec C, 7 Marks): "Explain file handling modes in Python."
  • 2025-26 (Sec C, 7 Marks): "What are file operations in Python? Explain the different modes used while opening a file."
  • 2024-25 (Sec C, 7 Marks): "Discuss different types of file modes in Python? Explain with examples."

2. Reading Files: read(), readline(), readlines()

read functions: Methods that move the file pointer forward while returning data from the current position.
read(n) → up to n characters (or the rest if n omitted); readline() → one line including its trailing newline; readlines() → list of all remaining lines.

File "sample.txt":     Hello
                       Python
                       File

f.read()        → 'Hello\nPython\nFile\n'
f.readline()    → 'Hello\n'   (next call → 'Python\n', at EOF → '')
f.readlines()   → ['Hello\n', 'Python\n', 'File\n']
for line in f:  → iterates one line at a time (memory efficient)
Function Return Type End of File Behaviour
read() str (one big string) returns ''
readline() str (one line) returns ''
readlines() list of strings returns []

After-Topic PYQs:

  • 2025-26 (Sec A, 2 Marks): "What are read() and readline() functions in file handling?"
  • 2023-24 (Sec A, 2 Marks): "What does the readline() function return when it reaches the end of a file?"
  • 2024-25 (Sec C, 7 Marks): "Write a program to read and write data from a text file. How do readline() and readlines() work? Explain with examples."

3. Writing Files: write() and writelines()

with open("out.txt", "w", encoding="utf-8") as f:
    n = f.write("Hello\n")          # returns 6 characters written
    f.writelines(["Asha\n", "Ravi\n"])  # list items concatenated as-is
  • write(s) writes the string s at the current pointer position and returns the number of characters written.
  • writelines(seq) writes every string in the sequence; it does not insert newline characters — each item must already contain \n.
  • In text mode, \n may be translated to the platform line ending; in binary mode you must write bytes, e.g. b"Hello".

After-Topic PYQs:

  • 2025-26 (Sec C, 7 Marks): "Describe file writing functions: write(), writelines(). Write a program to write student records to a file."
  • 2025-26 (Sec C, 7 Marks): "Write a Python program to create a file and write multiple lines into it."
  • 2023-24 (Sec C, 7 Marks): "Explain different file opening modes also write a Python Program to read a file and capitalize the first letter of every word in the file."

4. File Pointer: tell() and seek()

File pointer: The internal position marking where the next read or write will occur. tell() returns that position; seek(offset, whence) moves it.

seek(offset, whence): whence = 0 → from start, 1 → from current position, 2 → from end. Example: f.seek(0) rewinds to the beginning; f.seek(0, 2) jumps to the end; f.seek(-10, 2) moves 10 bytes back from the end (binary mode).

with open("data.txt", "r+", encoding="utf-8") as f:
    print(f.tell())       # 0
    print(f.read(5))      # first five characters
    print(f.tell())       # 5
    f.seek(0)             # rewind
    print(f.readline())   # first line again

After-Topic PYQs:

  • 2025-26 (Sec A, 2 Marks): "What is a file pointer in Python?"
  • 2024-25, 2025-26 (Sec C, 7 Marks): "What is the purpose of the seek() method in file handling? Demonstrate a program that copies content from one file to another."
  • 2025-26 (Sec C, 7 Marks): "Explain manipulating file pointer using seek(). Write a program to read last n lines from a file."

Solved Exam-Ready Questions

Solved Q1 (2024-25, 2025-26 Sec C — 7 Marks | Survival Mode)

Q: What is the purpose of the seek() method in file handling? Demonstrate a program that copies content from one file to another.

Solution:

  • Purpose: seek(offset, whence) repositions the file pointer so the next read/write happens elsewhere. seek(0) rewinds; seek(0,2) goes to the end; tell() reports the current position.
  • Copy program:
with open("source.txt", "r", encoding="utf-8") as src, \
     open("target.txt", "w", encoding="utf-8") as dst:
    for line in src:            # reads one line at a time
        dst.write(line)         # writes exactly what was read
print("File copied successfully")
  • Explanation: r opens the source for reading and w creates/overwrites the target; iterating line-by-line avoids loading a huge file into memory; with closes both files automatically.

Solved Q2 (2024-25, 2023-24 Sec C — 7 Marks)

Q: Write a program to reverse the contents of a file character by character, separating each character with a comma.

Solution:

with open("input.txt", "r", encoding="utf-8") as f:
    data = f.read()

reversed_data = ",".join(reversed(data))

with open("output.txt", "w", encoding="utf-8") as f:
    f.write(reversed_data)

print(reversed_data)

Trace: if input.txt contains Hello!!, reversed(data) yields ! ! o l l e H (individual characters), and ",".join(...) produces !,!,o,l,l,e,H. The 2023-24 variant expects Hello!! → H,e,l,l,o,!,! (original order with commas); for that, use ",".join(data.strip()). State clearly which direction the question expects.


Solved Q3 (2024-25 Sec C — 7 Marks)

Q: Explain file handling modes in Python.

Solution:

  • r: read-only text; fails with FileNotFoundError if absent.
  • w: write-only text; creates or truncates the file; pointer at start.
  • a: append text; creates if absent; pointer at end, so existing content survives.
  • x: exclusive creation; fails if the file already exists.
  • r+, w+, a+: add both reading and writing with the starting positions as in r, w, a.
  • b: binary mode (rb, wb, ab) for images/executables and byte data; t is the default text mode.
  • Example: open("log.txt","a") adds a new line to a log; open("report.txt","w") regenerates a report from scratch.
  • Best practice: use with so the file is always closed.

Solved Q4 (2024-25 Sec C — 7 Marks)

Q: Write a program to read and write data from a text file. How do readline() and readlines() work? Explain with examples.

Solution:

with open("in.txt", "r", encoding="utf-8") as f:
    first = f.readline()          # one line including '\n'
    rest = f.readlines()          # remaining lines as a list

with open("out.txt", "w", encoding="utf-8") as f:
    f.write(first.upper())
    f.writelines([line.upper() for line in rest])

Explanation: readline() advances the pointer by one line and returns '' at EOF; readlines() returns a list of line strings including their newline characters. write() takes one string; writelines() takes an iterable of strings and does not add separators, so each element must already end with \n. For in.txt = "hello\nworld\n": first = "hello\n", rest = ["world\n"], output contains HELLO\nWORLD\n.


Solved Q5 (2023-24 Sec C — 7 Marks)

Q: Write a Python program to read a file named "ABC.txt" and count the number of lines, words, and characters in the file.

Solution:

lines = words = chars = 0
with open("ABC.txt", "r", encoding="utf-8") as f:
    for line in f:
        lines += 1
        chars += len(line)
        words += len(line.split())

print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)

Reasoning: iterating the file yields one line per iteration; len(line) counts characters including the trailing newline; line.split() separates on whitespace so len(...) is the word count. For a file with "Python is fun\nFile handling\n": lines 2, words 5, characters 27 (13 + 14 including newlines — verify against the exact file).


Solved Q6 (2025-26 Sec C — 7 Marks)

Q: Describe file writing functions: write(), writelines(). Write a program to write student records to a file.

Solution:

students = [("21", "Asha", "88"), ("22", "Ravi", "72")]
with open("students.txt", "w", encoding="utf-8") as f:
    f.write("Roll Name Marks\n")              # header
    for roll, name, marks in students:
        f.write(f"{roll} {name} {marks}\n")   # one record per line
    f.writelines(["End of records\n"])        # writes the list item as-is

Explanation: write() writes one string and returns the number of characters written; writelines() accepts a sequence of strings but inserts no newlines, hence each record explicitly includes \n. Use mode a instead of w to add more records later without erasing existing ones.


Solved Q7 (2025-26 Sec C — 7 Marks)

Q: Explain manipulating file pointer using seek(). Write a program to read last n lines from a file.

Solution:

def last_n_lines(filename, n):
    with open(filename, "r", encoding="utf-8") as f:
        lines = f.readlines()          # list of all lines
        return lines[-n:]              # slice the final n entries

print(last_n_lines("data.txt", 3))

Pointer explanation: seek(0) returns to the start before re-reading; tell() shows the current offset; for large files a memory-efficient approach uses f.seek(0, 2) to find the end, then reads backwards in chunks until n newlines are counted. The slice version is simpler and is acceptable for exam-sized files: with 7 lines and n=3, lines 5–7 are returned.


Solved Q8 (2023-24 Sec C — 7 Marks)

Q: Explain different file opening modes also write a Python Program to read a file and capitalize the first letter of every word in the file.

Solution:

with open("article.txt", "r", encoding="utf-8") as f:
    text = f.read()

words = [w[:1].upper() + w[1:] for w in text.split(" ")]

with open("article_cap.txt", "w", encoding="utf-8") as f:
    f.write(" ".join(words))

Explanation: modes: r read, w write/overwrite, a append, r+ / w+ / a+ read+write, b binary. The program reads the whole text, splits on spaces, uppercases the first character of each word while preserving the rest, and writes the joined result to a new file with w. For "python file handling" → "Python File Handling".


Practice Questions (Self-Test)

  1. (2 Marks) What does readline() return at end of file? (Ans: empty string '')
  2. (2 Marks) What is the difference between write() and writelines()?
  3. (7 Marks) Write a program to print only words made entirely of digits from a file.
  4. (7 Marks) Write a program that reads ABC.txt and prints its first five characters, then rewinds and prints the first line using seek(0).
  5. (7 Marks) Write a program to create marks.txt and store five student names and marks using write().
  6. (7 Marks) Write a program to change all numbers in a file into words (e.g. 2 → two) using a dictionary lookup.
  7. (7 Marks) Explain with, tell() and seek() with one short program each.