Python Modules, File Handling, and
Iterators – Interview Q&A
🔹 Modules and Packages
1. Q: What are modules and packages in Python?
Answer: A module is a single Python file with functions, classes, or variables.
A package is a directory containing multiple modules with an __init__.py file.
2. Q: How do you import modules in Python?
Answer: Use `import module_name` or `from module_name import something`.
3. Q: What is the difference between import and from-import?
Answer: `import module` imports the whole module.
`from module import func` imports a specific function or class from the module.
4. Q: What is name == "main"?
Answer: `if __name__ == '__main__'` ensures that some code runs only when the file is
executed directly, not when imported as a module.
5. Q: How do you create a package?
Answer: Create a directory with an __init__.py file and add modules in it.
Example:
my_package/__init__.py
my_package/module.py
6. Q: What are built-in Python modules you have used?
Answer: Examples: os, sys, math, datetime, json, re, random, collections, itertools
🔹 File Handling
7. Q: How do you open and close files in Python?
Answer: Using open():
f = open('file.txt', 'r')
...
f.close()
or use `with` which closes automatically.
8. Q: What are the different file modes?
Answer: 'r' - read, 'w' - write, 'a' - append, 'b' - binary, 'x' - exclusive create, '+' - read/write
9. Q: How do you read and write to files?
Answer: f.read(), f.readline(), f.readlines()
f.write('text')
10. Q: What are context managers and the 'with' statement?
Answer: Context managers manage resources like files. The `with` statement ensures the file
is closed automatically:
with open('file.txt', 'r') as f:
data = f.read()
11. Q: How do you handle file exceptions?
Answer: Use try-except block:
try:
f = open('file.txt')
except FileNotFoundError:
print('File not found')
🔹 Iterators and Generators
12. Q: What are iterators?
Answer: An iterator is an object with __iter__() and __next__() methods.
It returns elements one at a time.
13. Q: How do you create an iterator?
Answer: Create a class with __iter__() and __next__():
class MyIter:
def __iter__(self): return self
def __next__(self): ...
14. Q: What is the difference between iterable and iterator?
Answer: Iterable has __iter__() and can be looped through (e.g., list).
Iterator is the object returned by iter(), and has __next__() method.
15. Q: What are generators and how do they differ from iterators?
Answer: Generators simplify iterator creation using the `yield` keyword.
They automatically create __iter__() and __next__() methods.
16. Q: How does the yield keyword work?
Answer: `yield` pauses the function and saves state between calls.
Example:
def gen():
yield 1
yield 2