MCS-201 · Unit 11

Functions and File Handling in Python

Section 7 of 8

Block 3 · Unit 11Functions and File Handling in Python13 min · Section 7 of 8

11.7Opening, Reading and Writing Files

Covers IGNOU MCS-201 §11.8, 11.8.1, 11.8.2

Main memory is volatile: everything in variables is lost when the program ends. Files store data permanently. Python’s file handling is simpler than C’s (Unit 8) but follows the same three steps: open, operate, close.

Text and binary files

Text fileBinary file
ContentsCharacters organised in lines ending with a newlineBytes with an application-specific structure
Opened with"r", "w", "a" (text is the default)Add b: "rb", "wb", "ab"
Python type of data readstrbytes
Examples.txt, .csv, .py, .htmlImages, PDFs, ZIP files

Every file is stored as bits; “text” means the bytes represent characters in an encoding such as UTF-8. Use encoding="utf-8" for portable text files.

Opening a file

Syntax
file_object = open(file_name, mode="r", encoding=None)

open() returns a file object used for all further operations. The modes:

ModeMeaningIf the file existsIf it does not exist
"r"Read (default)Read from the startFileNotFoundError
"w"WriteErased firstCreated
"a"AppendWrites go to the endCreated
"x"Exclusive createFileExistsErrorCreated
"r+"Read and writeKeptFileNotFoundError
"w+"Write and readErased firstCreated
"a+"Append and readWrites go to the endCreated

Add b for binary ("rb", "wb", …).

Reading and writing

MethodWhat it does
read()Rest of the file as one string
read(n)Next n characters, from the current position
readline()Next line, including its "\n"; "" at the end of the file
readlines()List of all remaining lines
for line in f:Loops over lines one at a time (memory-efficient)
write(s)Writes the string s (adds no newline) and returns the number of characters written
writelines(list)Writes each string in the list (adds no newlines)
tell()Current position
seek(pos)Moves to position pos (0 is the start)
close()Flushes and closes the file

The with statement

with open(...) as f: opens the file, runs the indented block and always closes the file when the block ends, even if an error occurs. It is the recommended way to work with files; no close() call is needed.

Key takeaways

  • open() returns a file object; text mode is the default, add b for binary.
  • "r", "w", "a", "x" and the + forms control reading, writing, erasing and creating.
  • read, readline, readlines, iteration, write, tell and seek operate on the file.
  • with closes the file automatically.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

Which mode creates a new file but fails if the file already exists?

Show answer

Answer: C. "x"

Exclusive-creation mode raises FileExistsError for an existing file. "w" would silently erase it.

Question 2 · multiple choice

What does readline() return at the end of a file?

Show answer

Answer: B. An empty string ""

An empty line in the middle of a file is "\n"; only the true end gives "".

Question 3 · multiple choice

What does this program print?

Python · quiz_file.py
with open("q.txt", "w") as f:
    f.write("ab")
    f.write("cd\n")
with open("q.txt", "a") as f:
    f.write("ef\n")
with open("q.txt") as f:
    print(len(f.readlines()), repr(f.read()))
Show answer

Answer: A. 2 ”

The file holds “abcd\n” and “ef\n”: two lines. After readlines() the position is at the end, so read() returns an empty string.

Question 4 · multiple choice

What is the main advantage of with open(...) as f:?

Show answer

Answer: D. It closes the file automatically when the block ends, even after an error

The with statement guarantees clean-up, so files are never left open.

Question 5 · multiple choice

What happens with open("missing.txt") if the file does not exist?

Show answer

Answer: C. FileNotFoundError is raised

The default mode "r" requires an existing file.

Question 6 · short answer

Write a program that copies only the non-empty lines of input.txt to output.txt.

Show worked answer

with open("input.txt") as src, open("output.txt", "w") as dst: followed by for line in src: if line.strip(): dst.write(line). Both files are opened in one with statement and closed automatically. line.strip() removes spaces and the newline; an empty result is falsy, so blank lines are skipped, and every other line is written unchanged (with its own newline).

↑ ↓ move↵ openTab switch type