Skip to content
C

Python Interview Questions

File Handling Interview Questions

Opening files, file modes, and why context managers are the safe way to work with them.

Question 1: How do you open a file?

Ans

Use open() with a mode and preferably a with statement so the file is closed automatically.

Example

python
with open("data.txt", "r", encoding="utf-8") as file: text = file.read() print(text)

Important Point

Specify encoding for text files when portability matters.

Question 2: What are common file modes?

Ans

r reads, w writes and truncates, a appends, x creates exclusively, and modes can be combined with b for binary or + for updating.

Example

python
with open("log.txt", "a", encoding="utf-8") as f: f.write("Started\n")

Important Point

`w` can destroy existing file contents, so use it deliberately.

Question 3: Why use with for files?

Ans

A context manager ensures the file resource is closed when the block exits, including when an exception occurs.

Example

python
with open("data.txt", encoding="utf-8") as f: first = f.readline()

Important Point

This pattern is safer than relying on garbage collection to close files.

Continue Your Preparation