Loading

Quipoin Menu

Learn • Practice • Grow

python / File I/O
interview

Q1. How do you open a file in Python?
Use the open() function with a filename and mode. Modes: 'r' (read), 'w' (write), 'a' (append), 'rb' (binary read), etc. Example:
file = open(''data.txt'', ''r'') content = file.read() file.close()
It's better to use the with statement for automatic closing.

Q2. How do you read a file?
Methods: read() reads entire file as string, readline() reads one line, readlines() returns list of lines. Example:
with open(''file.txt'') as f: lines = f.readlines()

Q3. How do you write to a file?
Use write() or writelines(). Open with 'w' to overwrite, 'a' to append. Example:
with open(''output.txt'', ''w'') as f: f.write("Hellon") f.writelines(["line1n", "line2n"])

Q4. What is the with statement?
The with statement simplifies resource management by automatically closing the file (or releasing other resources) when the block exits. It uses context managers. Example:
with open(''file.txt'') as f: data = f.read()

Q5. What is the difference between binary and text mode?
Text mode (default) reads/writes strings, handles newline conversion, and uses encoding. Binary mode ('b') reads/writes bytes, no encoding, and is necessary for non-text files like images, PDFs. Use 'rb' or 'wb' for binary files.