0% found this document useful (0 votes)
10 views3 pages

Python File Handling Interview Q&A

The document provides a series of interview questions and answers related to Python modules, file handling, and iterators. It covers topics such as the definition and creation of modules and packages, file operations, and the concepts of iterators and generators. Key points include the use of the 'with' statement for file handling and the role of the 'yield' keyword in generator functions.

Uploaded by

Rinki Kumari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Python File Handling Interview Q&A

The document provides a series of interview questions and answers related to Python modules, file handling, and iterators. It covers topics such as the definition and creation of modules and packages, file operations, and the concepts of iterators and generators. Key points include the use of the 'with' statement for file handling and the role of the 'yield' keyword in generator functions.

Uploaded by

Rinki Kumari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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/[Link]

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('[Link]', 'r')
...
[Link]()

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: [Link](), [Link](), [Link]()


[Link]('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('[Link]', 'r') as f:
data = [Link]()

11. Q: How do you handle file exceptions?

Answer: Use try-except block:


try:
f = open('[Link]')
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

Common questions

Powered by AI

The 'yield' keyword simplifies iteration by allowing a function to return a value and pause its state, which can be resumed later to return subsequent values. This method is particularly suitable in scenarios where maintaining and iterating over large datasets might be computationally expensive or memory-constrained. 'Yield' is preferable over other techniques because it does not require the entire dataset to be loaded in memory simultaneously, instead fetching data on-demand, which is ideal for streaming data or large file processing.

Common built-in modules in Python include os, sys, math, datetime, json, re, random, collections, and itertools. Familiarity with these modules benefits Python development by providing essential tools for efficient code writing and problem-solving across various use cases. For example, 'os' and 'sys' for system operations, 'json' for data interchange, 'math' for mathematical functions, and 're' for regular expressions. Understanding these modules allows developers to leverage Python's comprehensive standard library, reducing the need for external dependencies and improving code integration and deployment.

File exceptions in Python are managed using the try-except block. For example, opening a file is encapsulated within a 'try' block to catch file-related exceptions like FileNotFoundError in case the file does not exist. Handling exceptions is critical in external file input/output operations as it prevents the program from crashing due to unforeseen file system issues, enables graceful error reporting, and robustly manages scenarios such as missing files or permission errors. This ensures the stability and reliability of the code upon encountering runtime issues.

An '__init__.py' file in a Python package is used to indicate that the directory contains a package, not just a regular directory. It can also execute initialization code for the package. This file's presence allows the Python interpreter to recognize the directory as a package so that modules within it can be accessed with the package's namespace. It affects module accessibility by controlling what gets imported with 'from package import *', as well as initializing package-wide data or state upon package import. Including '__init__.py' ensures that a clean namespace is maintained, and any necessary setup is completed when the package is imported.

To create a Python package, you must create a directory with an '__init__.py' file, which can be empty or include initialization code, and then add module files to this directory. The benefits of using a package over individual modules in collaborative software are extensive and methodical organization of code, easier maintenance and refactoring, and the ability to clearly separate different components or functionalities in a large codebase. Packages also facilitate the reuse of modular components across various projects, encouraging team collaboration and version control.

The 'if __name__ == "__main__"' construct in Python is used to determine whether a Python file is being run as the main program or is imported as part of another module. This construct is useful because it allows developers to define certain code to execute only when the script is run directly, not when imported. This is especially useful in creating standalone scripts, as it can contain code intended for testing or execution that should not be executed when the module's functions or classes are reused elsewhere.

Generators are preferred over traditional iterator classes when the function to be iterated is complex or involves sequences of large data that do not need to be stored in memory all at once. Generators, using the 'yield' keyword, manage the state efficiently between subsequent calls, thus enabling large datasets to be handled with less memory overhead. They also reduce boilerplate code needed for defining iterator classes and functions with '__iter__'() and '__next__'(), making code cleaner and more readable.

Creating a custom iterator in Python involves defining a class with '__iter__()' and '__next__()' methods. The '__iter__()' method should return the iterator object itself, while the '__next__()' method should return the next item from the sequence, and raise StopIteration once all items have been returned. Compared to using built-in iterators, custom iterators allow for more control over iteration logic and can be tailored to specific use cases that built-in iterators cannot achieve. However, built-in iterators are pre-optimized and save development time, and they are often sufficient for common iterable operations.

In Python, importing modules is performed using two main syntaxes: 'import module' imports the entire module into the namespace and requires referencing the module to access its attributes, e.g., module.func(). 'From module import func' imports a specific attribute, which can be used directly without module reference. The main impact of these methods on namespace and code execution is that 'import module' might use more memory by loading the entire module, whereas 'from module import func' loads only specific components, potentially saving memory. Furthermore, 'import module' ensures the whole module's functionality is available, whereas specific imports may result in faster execution due to reduced namespace cluttering.

Context managers enhance file handling by ensuring that resources are correctly managed and released after their use, avoiding resource leaks. When using the 'with' statement, files are automatically closed upon exiting the block, which reduces the chance of encountering errors due to files being left open. Compared to traditional methods where files must be manually closed using 'f.close()', context managers handle exceptions more gracefully. Even if an error occurs within the block, the file is closed properly, which reduces both boilerplate code and the potential for file-handling-related errors.

You might also like