NEW
Font size
WorksheetsLECTURE 05 Quizs (25.11.2025)
Total questions: 20
Worksheet time: 10mins
What does the 'r' mode signify when opening a file in Python?
Write mode
Read mode
Append mode
Binary mode
Which Python object allows you to read CSV files as dictionaries?
csv.reader
csv.DictReader
csv.writer
csv.DictWriter
Which method would you use with a `Path` object to check if a directory exists?
exists()
is_dir()
is_file()
mkdir()
Write a Python code snippet that safely reads a file and ensures it is closed even if an exception occurs. Test your code in a compiler.
```python try: with open('example.txt', 'r') as f: print(f.read()) except Exception as e: print("Error:", e) ```
```python with open('example.txt', 'r') as f: print(f.read()) raise Exception("Error!") ```
```python open('example.txt', 'r') print(f.read()) ```
```python try: open('example.txt', 'r') print(f.read()) except Exception as e: print("Error:", e) ```
Write a Python code snippet to read each row of a CSV file as a dictionary using `csv.DictReader`. Test your code in a compiler and check the output.
```python import csv with open('file.csv', 'r') as f: reader = csv.DictReader(f) for row in reader: print(row) ```
```python import csv with open('file.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row) ```
```python import csv with open('file.csv', 'w') as f: reader = csv.DictReader(f) for row in reader: print(row) ```
```python import csv reader = csv.DictReader('file.csv') for row in reader: print(row) ```
True or False: Using the `with open()` statement in Python ensures that the file is closed automatically after the block is executed.
True
False
Write a Python code snippet that demonstrates how a context manager ensures a file is closed even if an error occurs. Test it in a compiler and observe the behavior.
```python try: with open('test.txt', 'r') as f: raise Exception("Error!") except Exception as e: print("Caught exception:", e) # File is closed automatically ```
```python with open('test.txt', 'r') as f: raise Exception("Error!") # File is not closed ```
```python open('test.txt', 'r') raise Exception("Error!") # File is closed automatically ```
```python try: open('test.txt', 'r') raise Exception("Error!") except Exception as e: print("Caught exception:", e) # File is closed automatically ```
Write a Python code snippet to demonstrate how `pathlib` improves code readability and maintainability for cross-platform file path operations compared to `os.path`. Test your code and explain your reasoning.
```python from pathlib import Path p = Path('folder') / 'file.txt' print(p) # pathlib uses objects and operators, making code more readable and cross-platform. ```
```python import os p = os.path.join('folder', 'file.txt') print(p) # os.path is more readable and modern. ```
```python from pathlib import Path p = Path('folder', 'file.txt') print(p) # pathlib is only for Windows. ```
```python import os p = os.path.join('folder', 'file.txt') print(p) # os.path is preferred for maintainability. ```
Which module is recommended for modern, object-oriented file and directory path handling in Python?
os.path
pathlib
shutil
sys
True or False: The `csv.DictReader` object reads each row of a CSV file as a dictionary, using the column headers as keys.
True
False
Write a Python code snippet that opens a file without a context manager and explain the potential issues. Then, rewrite the code using a context manager to fix the problem. Test both in a compiler.
```python # Without context manager f = open('test.txt', 'r') print(f.read()) # Potential issue: file may not be closed properly. # With context manager with open('test.txt', 'r') as f: print(f.read()) # File is closed automatically. ```
```python # Without context manager open('test.txt', 'r') print(f.read()) # No issues. # With context manager with open('test.txt', 'r') as f: print(f.read()) # No difference. ```
```python # Without context manager f = open('test.txt', 'r') print(f.read()) # File is encrypted. # With context manager with open('test.txt', 'r') as f: print(f.read()) # File is encrypted. ```
```python # Without context manager f = open('test.txt', 'r') print(f.read()) # File is deleted. # With context manager with open('test.txt', 'r') as f: print(f.read()) # File is deleted. ```
Write a Python code snippet to process each row of a CSV file as a dictionary and explain why using `csv.DictReader` is beneficial. Test your code and reasoning.
```python import csv with open('data.csv', 'r') as f: reader = csv.DictReader(f) for row in reader: print(row) # DictReader maps column headers to keys, making access easier. ```
```python import csv with open('data.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row) # DictReader is slower than reader. ```
```python import csv reader = csv.DictReader('data.csv') for row in reader: print(row) # DictReader is not recommended. ```
```python import csv with open('data.csv', 'w') as f: reader = csv.DictReader(f) for row in reader: print(row) # DictReader is for writing only. ```
Which of the following is NOT a benefit of using a context manager for file operations?
Automatic resource cleanup
Cross-platform path handling
Error handling
Preventing resource leaks
True or False: The `pathlib` module is designed for cross-platform file path operations in Python.
True
False
Which of the following is a standard practice to guarantee that file resources are safely released after use?
try...finally block
os.close()
with open(...) (Context Manager)
Using pathlib.Path
True or False: If you open a file with `open()` but forget to call `close()`, the operating system will always immediately free the resource.
True
False
Write a Python code snippet using a context manager to open a file named "settings.json" for reading and print its contents. Run your code in a Python compiler, then check the answer below.
```python with open('settings.json', 'r') as f: print(f.read()) ```
```python open('settings.json', 'r') print(f.read()) ```
```python with open('settings.json', 'w') as f: print(f.read()) ```
```python open('settings.json', 'w') print(f.read()) ```
Write a Python code snippet using `pathlib` to create a `Path` object for a file named "data.csv". Test it in a Python compiler and verify the result.
```python from pathlib import Path p = Path('data.csv') print(p) ```
```python import os p = os.path('data.csv') print(p) ```
```python from pathlib import Path p = pathlib.Path('data.csv') print(p) ```
```python p = file.Path('data.csv') print(p) ```
Write a Python code snippet using `pathlib` to iterate through all ".txt" files in a directory and print their contents safely. Test your code in a compiler.
```python from pathlib import Path for file in Path('.').glob('*.txt'): with open(file, 'r') as f: print(f.read()) ```
```python import os for file in os.listdir('.'): if file.endswith('.txt'): open(file, 'r') print(f.read()) ```
```python from pathlib import Path for file in Path('.').glob('*.txt'): print(file.read()) ```
```python import shutil for file in shutil.copy('.'): if file.endswith('.txt'): print(file) ```
Write a Python code snippet using `pathlib` to check if a directory named "my_folder" exists. Test it in a compiler and verify the result.
```python from pathlib import Path p = Path('my_folder') print(p.is_dir()) ```
```python from pathlib import Path p = Path('my_folder') print(p.exists()) ```
```python import os print(os.path.isdir('my_folder')) ```
```python from pathlib import Path p = Path('my_folder') print(p.is_file()) ```
