Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Python 10 questions

File Handling & Context Managers

File Handling & Context Managers. Read and write files, handle binary streams, manage file pointers, and write custom context managers using the with block.

More Python
Interview questions 1–10 of 10
1

What are the different file open modes in Python?

ModeMeaning'r'Read (default) - error if file doesn't exist'w'Write - creates file, TRUNCATES (erases) existing...

Read answer →
2

Why should you use the 'with' statement when working with files?

The 'with' statement guarantees the file is closed automatically, even if an exception occurs, preventing reso...

Read answer →
3

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

MethodReturnsMemory usageread()Entire file content as one stringHigh for large files - loads everythingreadlin...

Read answer →
4

How do you read and write JSON and CSV files in Python?

# JSON - using the built-in json module import json data = {'name': 'John', 'age': 30, 'active': True} # Wri...

Read answer →
5

How do you write a custom context manager using __enter__ and __exit__?

A class becomes usable with 'with' by implementing __enter__ (setup, returns the value bound to 'as') and __ex...

Read answer →
6

How does the contextlib module simplify writing context managers?

The contextlib.contextmanager decorator lets you write a context manager using a generator function instead of...

Read answer →
7

How do you handle file paths in a cross-platform way using pathlib?

pathlib.Path provides an object-oriented, cross-platform way to work with file paths, replacing manual string...

Read answer →
8

What is the difference between text mode and binary mode when working with files?

ModeData returnedHandlesText mode ('r', 'w')strAutomatic encoding/decoding, newline translationBinary mode ('r...

Read answer →
9

How do you handle large files efficiently in Python without running out of memory?

The key principle is to avoid loading the entire file into memory at once - process it in chunks or line by li...

Read answer →
10

What happens if you don't close a file properly, and how do you check if a file is closed?

Failing to close files can lead to resource leaks, data not being flushed to disk (partial writes), and eventu...

Read answer →