Placement Prep

File Handling in Python: Open, Read, Write, Delete

Master Python file handling for placement exams. Covers open modes, the with statement, read/write methods, and the os module with runnable examples.

By FACE Prep Team 4 min read
python file-handling placement-prep python-programs technical-interview

Python file handling covers five operations: creating, opening, reading, writing, and deleting files stored on disk.

These operations show up in placement MCQ rounds for IT services companies, and the concepts transfer directly to any automation script or data pipeline you will build later.

Why File Handling Appears in Placement Exams

IT services companies test file handling in their online assessments because it sits at the intersection of Python syntax and practical programming logic. A candidate who understands modes, context managers, and read methods has demonstrated they can write scripts that interact with real systems, not just solve isolated coding puzzles.

The three most common MCQ patterns are:

  • Mode traps: “What happens when you open a non-existent file in w mode?” (creates it) vs. r mode (raises FileNotFoundError).
  • Context manager logic: “Which statement ensures a file is closed even if an exception occurs?”
  • Method return type: “What does readlines() return?” (a list of strings, not a single string).

If you are building a broader Python base first, the Python example programs collection covers the foundational patterns these tests draw from.

File Modes in Python

Every open() call requires a mode string. The mode controls access level and file position.

ModeFull nameCreates file if missing?Overwrites existing?Binary?
rReadNo (raises error)NoNo
wWriteYesYesNo
aAppendYesNo (adds to end)No
rbRead binaryNo (raises error)NoYes
wbWrite binaryYesYesYes
abAppend binaryYesNo (adds to end)Yes

Text modes (r, w, a) decode bytes to strings using the platform default encoding. Binary modes (rb, wb, ab) read and write raw bytes, which is what you need for images, PDFs, or any file where encoding does not apply.

The Python 3 documentation on reading and writing files lists additional mode combinations (r+, w+, a+) for simultaneous read-write access, though the six modes above cover most placement questions.

The with Statement: Safer Than Manual Close

The naive approach to opening a file looks like this:

f = open("data.txt", "r")
content = f.read()
f.close()

The problem: if f.read() raises an exception, f.close() never runs. The file handle stays open, which wastes system resources and can corrupt data being written.

The with statement, introduced in PEP 343, solves this by wrapping the file in a context manager:

with open("data.txt", "r") as f:
    content = f.read()
# f is automatically closed here, even if read() raised an error

When execution leaves the with block for any reason (normal exit, exception, or return), Python calls the file object’s __exit__ method, which closes the file. This is not a style preference. In production code and in technical interviews, bare open() without with is considered incorrect.

Reading File Content: Three Methods

Given a file notes.txt containing:

Python is practical.
File handling is common in placement tests.
The with statement is key.

read()

with open("notes.txt", "r") as f:
    content = f.read()
print(content)

read() returns the entire file as one string, including newline characters. Pass an integer to read that many characters: f.read(6) returns "Python".

readline()

with open("notes.txt", "r") as f:
    first_line = f.readline()
    second_line = f.readline()

Each readline() call advances the file pointer by one line. Calling it in a loop is the standard way to process large files without loading everything into memory.

readlines()

with open("notes.txt", "r") as f:
    lines = f.readlines()
print(lines)
# ['Python is practical.\n', 'File handling is common in placement tests.\n', 'The with statement is key.\n']

readlines() returns a list of strings. Each string includes its trailing \n. Use line.strip() inside a loop to remove whitespace.

After reading file content line by line, character classification is a natural next step for filtering or categorising what you find.

Writing, Appending, and Deleting

Writing to a file

with open("log.txt", "w") as f:
    f.write("Session started\n")

write() accepts a single string. It does not add a newline automatically. To write multiple lines at once, use writelines() with a list:

lines = ["Line one\n", "Line two\n", "Line three\n"]
with open("log.txt", "w") as f:
    f.writelines(lines)

Remember: w mode overwrites. If log.txt already contains data, it is gone.

Appending to a file

with open("log.txt", "a") as f:
    f.write("New entry added\n")

a mode moves the write pointer to the end of the file. Existing content is preserved.

Deleting and checking existence

The os module handles file-system operations outside the scope of open():

import os

# Check before acting
if os.path.exists("log.txt"):
    os.remove("log.txt")
    print("File deleted")
else:
    print("File not found")

os.remove() deletes permanently; there is no recycle bin. os.path.exists() prevents a FileNotFoundError when the file may or may not be present. A solid pattern for production scripts and something examiners sometimes ask about in technical rounds.

For more hands-on Python programs with similar input-output patterns, the Python calculator program walkthrough covers function design and user input handling in the same style.

From File Parsing to LLM Pipelines

The with open(...) as f: pattern does more than pass placement tests. When you start feeding structured text into an LLM, the first practical step is usually reading a file, parsing its lines, and sending batches to an API. The context manager pattern keeps that pipeline clean: files close on exception, memory stays predictable, and the code is readable by the next person who touches it.

TinkerLLM is where that next step becomes concrete. For 299 rupees, you get real LLM API calls and a working project to build, so the file-parsing logic you just learned connects directly to something you can put in a portfolio rather than a practice folder.

Primary sources

Frequently asked questions

What is the difference between r, r+, and rb mode in Python?

r opens a text file for reading only and raises FileNotFoundError if the file does not exist. r+ opens a text file for both reading and writing. rb opens a binary file for reading, useful for images, PDFs, and other non-text formats.

What happens if you open a file in w mode but the file does not exist?

Python creates the file automatically. This is a common MCQ trap: w mode creates missing files, while r mode raises FileNotFoundError. Always confirm mode behaviour before a placement test.

What is the difference between read() and readlines()?

read() returns the entire file content as a single string. readlines() returns a list of strings, one per line, with newline characters included. Use readlines() when you need to iterate over lines individually.

Why use with open() instead of f = open() followed by f.close()?

The with statement guarantees the file is closed when the block exits, including on exceptions. Bare open() plus close() leaves the file open if an error occurs between the two calls, which can cause data corruption or resource leaks.

How do I check if a file exists before opening it in Python?

Use os.path.exists('filename.txt') from the os module. It returns True if the path exists and False if it does not, letting you branch logic safely before attempting to open or delete the file.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF