Python File Handling and OOP Exam Questions with Detailed Answers, Exams of Object Oriented Programming

A comprehensive set of questions and answers related to file handling, exceptions, and object-oriented programming (oop) in python. It covers topics such as file input/output, exception handling, context managers, oop principles, data serialization with csv and json files, and applied code scenarios. Each question includes a detailed rationale for the correct answer, making it an ideal resource for exam preparation and hands-on python mastery. The material is designed to help students understand and apply key concepts in python programming, enhancing their ability to debug and interpret file-based logic questions. This resource is particularly useful for those preparing for exams or seeking to deepen their understanding of python scripting and programming foundations. It provides practical insights and clear explanations that facilitate effective learning and skill development in python.

Typology: Exams

2025/2026

Available from 10/30/2025

proflean
proflean 🇺🇸

3.1

(7)

2.3K documents

1 / 43

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1 | P a g e
WGU D278 OA – File Handling, Exceptions,
and Object-Oriented Programming | Full
Objective Assessment (2025 Edition)
Comprehensive Real Question Final Exam | Python Scripting & Programming
Foundations | Verified Answers with Detailed Rationales
Overview:
This WGU D278 Scripting and Programming Foundations File Handling & OOP Master
Exam (2025) is a complete actual -question objective assessment designed to mirror the real
WGU D278 OA.
It provides full coverage of:
Python File Input/Output (I/O) Reading, writing, appending, and managing text and
binary files
Exception Handling & Error Recovery Using try, except, else, and finally
correctly
Context Managers and Resource Management Safe file closing and automation with
with statements
Object-Oriented Programming (OOP) Classes, inheritance, polymorphism,
encapsulation, and class methods
Data Serialization Working with CSV and JSON files
Applied Code Scenarios Debugging and interpreting file-based logic questions
Each question includes bolded correct answers and detailed rationales, making it ideal for
both exam preparation and hands-on Python mastery.
1. Which mode opens a file for writing, erasing its contents if it already exists?
A) 'r'
B) 'w'
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b

Partial preview of the text

Download Python File Handling and OOP Exam Questions with Detailed Answers and more Exams Object Oriented Programming in PDF only on Docsity!

WGU D278 OA – File Handling, Exceptions,

and Object-Oriented Programming | Full

Objective Assessment (2025 Edition)

Comprehensive Real Question Final Exam | Python Scripting & Programming Foundations | Verified Answers with Detailed Rationales Overview: This WGU D278 Scripting and Programming Foundations – File Handling & OOP Master Exam (2025) is a complete actual - question objective assessment designed to mirror the real WGU D278 OA. It provides full coverage of:  Python File Input/Output (I/O) – Reading, writing, appending, and managing text and binary files  Exception Handling & Error Recovery – Using try, except, else, and finally correctly  Context Managers and Resource Management – Safe file closing and automation with with statements  Object-Oriented Programming (OOP) – Classes, inheritance, polymorphism, encapsulation, and class methods  Data Serialization – Working with CSV and JSON files  Applied Code Scenarios – Debugging and interpreting file-based logic questions Each question includes bolded correct answers and detailed rationales , making it ideal for both exam preparation and hands-on Python mastery.

1. Which mode opens a file for writing, erasing its contents if it already exists? A) 'r' B) 'w'

C) 'a' D) 'r+' Rationale 'w' mode overwrites the existing file or creates a new one.

2. What will happen if you try to open a non-existent file using open('missing.txt', 'r')? A) It creates a new file. B) It prints “File not found.” C) It raises a FileNotFoundError. D) It returns an empty string. Rationale Reading a non-existent file triggers FileNotFoundError. 3. What does the 'a' mode do in open()? A) Opens file for reading. B) Opens file for appending data at the end. C) Opens file for writing from start. D) Opens file in binary mode. Rationale 'a' mode appends new content without overwriting. 4. What is the correct way to close an opened file in Python? A) file.stop() B) close(file) C) file.close() D) end(file) Rationale The .close() method closes the file stream.

8. Which method returns a list of all lines in a file? A) read() B) readlines() C) readline() D) lines() Rationale readlines() loads each line as an element of a list. 9. What does 'b' indicate in a file mode string like 'rb'? A) Backup B) Binary mode C) Both read and write D) Background Rationale 'b' means the file is opened in binary mode. 10. Which statement correctly writes multiple lines to a file? lines = ["A\n", "B\n", "C\n"] A) file.write(lines) B) file.add(lines) C) file.writelines(lines) D) file.append(lines) Rationale .writelines() writes a list of strings to a file. 11. What does the following code do? f = open("notes.txt", "r+")

f.write("Test") A) Reads the file only. B) Opens file for both reading and writing. C) Creates a new file only. D) Raises an error. Rationale 'r+' allows both reading and writing without truncating.

12. What exception is raised when trying to write to a file opened in 'r' mode? A) FileNotFoundError B) EOFError C) io.UnsupportedOperation D) TypeError Rationale Writing is not supported in read-only mode. 13. Why is it good practice to use a with open() statement? A) It makes code shorter. B) It automatically closes files after use. C) It reads faster. D) It requires fewer arguments. Rationale The with block handles cleanup automatically. 14. What happens if .close() is not called on a file object? A) File is deleted. B) Data may not be saved properly. C) Python crashes. D) Nothing changes.

18. Which mode will allow you to add new content but not erase old data? A) 'w' B) 'a' C) 'r' D) 'x' Rationale Append mode 'a' adds to the end without deleting data. 19. Which mode creates a new file and fails if it already exists? A) 'w' B) 'r+' C) 'a' D) 'x' Rationale 'x' is exclusive creation mode. 20. Which command writes a single line to a file? A) write.line() B) f.write("Hello\n") C) f.addline("Hello") D) f.println("Hello") Rationale .write() outputs strings to files. 21. What is returned by f.read() if the file cursor is already at the end? A) "EOF" B) None

C) '' (empty string) D) False Rationale Reading past EOF returns an empty string.

22. What does seek(0) do? A) Deletes the file B) Moves the file pointer to the beginning C) Saves data to disk D) Rewinds one character Rationale seek(0) resets cursor position. 23. What will this code output? try: f = open("demo.txt", "x") except FileExistsError: print("Already exists") A) Creates new file B) Prints “Already exists” if file exists C) Deletes file D) Raises IOError Rationale 'x' mode throws FileExistsError if file is present. 24. When reading a large file efficiently, which approach is best? A) Use .read() once B) Loop through file line by line C) Convert it to a list D) Use recursion

Rationale File objects have a Boolean property .closed.

28. What is the output of this code? try: f = open("data.txt", "r") content = f.read() except FileNotFoundError: print("Missing file") else: print("File read successfully") A) Always prints “Missing file.” B) Prints “File read successfully” if file exists. C) Causes runtime error. D) Skips both messages. Rationale The else block runs only if no exception occurs. 29. Which method reads a single character from a file? A) readline() B) readlines(1) C) read(1) D) next() Rationale The read(size) method reads up to the specified number of bytes or characters. 30. The "rb" and "wb" file modes are primarily used for: A) JSON data B) Text encoding

C) Binary files (e.g., images, audio) D) CSV manipulation Rationale "rb" and "wb" handle non-text, raw binary data streams.

31. What happens when you attempt to write to a file opened in "r" mode? A) Data is appended. B) File is truncated. C) Raises an exception. D) Automatically switches to write mode. Rationale "r" is read-only mode; writing causes an io.UnsupportedOperation error. 32. How would you safely read data and close the file automatically? A) f = open("file.txt") data = f.read() f.close() B) data = open("file.txt").read() C) with open("file.txt", "r") as f: data = f.read() D) None of the above Rationale The with block ensures proper file closure automatically.

36. What type of Python object is typically returned from json.load()? A) String B) File object C) Dictionary or list D) Tuple Rationale JSON maps objects → dicts, and arrays → lists in Python. 37. Which of these file paths works correctly on all operating systems? A) "C:\new\data.txt" B) "C:\new\data.txt" C) "/C/new/data.txt" D) "/new/data.txt" Rationale Escape backslashes or use r"raw strings" to avoid syntax issues. 38. What will this code do? with open("test.txt", "a") as f: f.write("Hello\n") f.write("World\n") A) Writes both lines. B) Raises a ValueError. C) Appends correctly. D) Overwrites file. Rationale The last f.write() is outside the with block — file is closed, causing ValueError. 39. Which method returns the file pointer’s current position?

A) locate() B) track() C) tell() D) position() Rationale tell() returns an integer showing the file cursor location.

40. What’s the difference between "a" and "a+" mode? A) No difference B) "a" allows read/write C) "a+" allows both reading and appending D) "a" overwrites file Rationale "a+" opens for reading and appending without truncating existing content. 41. What does this code do? with open("report.txt", "r") as f: for line in f: print(line.strip()) A) Prints only the first line. B) Skips every second line. C) Prints all lines without extra newlines. D) Produces an error. Rationale Iterating directly over a file reads it line by line; strip() removes \n. 42. Which function checks if a file exists before opening it? A) file.exists() B) os.path.exists("file.txt") C) open.exists() D) os.file("file.txt")

45. What’s the output? try: open("file.txt", "x") open("file.txt", "x") except FileExistsError: print("Exists") A) Creates file twice. B) Prints “Exists.” C) Overwrites file. D) Raises ValueError. Rationale Mode "x" creates new files and raises FileExistsError if the file already exists. 46. What will this display? try: with open("data.txt", "r") as f: lines = f.readlines() except: print("Problem") else: print(len(lines)) A) Always prints “Problem.” B) Prints the number of lines if file exists. C) Throws NameError. D) Never runs. Rationale else executes only when no error occurs. 47. Which statement writes each element of a list to a new line in a file?

data = ["A", "B", "C"] A) f.write(data) B) f.writelines(data) C) f.writelines(item + "\n" for item in data) D) for data in f: write() Rationale A generator expression adds newline after each element.

48. In which mode will read() return an empty string? A) "r+" B) "r" C) "a" D) "w" Rationale In append mode the pointer starts at end of file, so read() yields nothing. 49. Which method removes a file from the filesystem? A) delete("file.txt") B) os.remove("file.txt") C) file.close() D) os.delete() Rationale os.remove() deletes files permanently. 50. What is printed? import os f = open("sample.txt", "w") f.write("Test") f.close()

Rationale Ensures data is physically written without waiting for auto-flush.

54. Why should you avoid using bare except: clauses? A) They slow code. B) They catch unintended exceptions and hide bugs. C) They require extra memory. D) They prevent loops. Rationale Always specify exception types to avoid masking errors. 55. What does this code do? import json with open("data.json", "w") as f: json.dump({"x": 10 }, f) A) Writes a Python dict. B) Serializes the dict to JSON format and saves it. C) Raises TypeError. D) Writes binary bytes. Rationale json.dump() translates Python objects → JSON text. 56. Which command replaces all file content with an empty string? A) truncate() B) f.truncate(0) C) os.clear() D) reset() Rationale truncate(0) removes all bytes from file.

57. What’s the purpose of try...finally in file I/O? A) To avoid with statements. B) To guarantee closure of resources even after errors. C) To speed up writes. D) To skip exceptions. Rationale finally runs no matter what—good for closing files or clean-up. 58. How can you copy a file in Python without reading it manually? A) os.copy() B) shutil.copy("a.txt","b.txt") C) path.copy() D) file.duplicate() Rationale shutil.copy() copies contents and metadata. 59. Which function lists all files in a directory? A) os.dir() B) os.listdir() C) os.show() D) os.scan() Rationale os.listdir() returns filenames within a given path. 60. Which statement is true about file buffers? A) They store data only in memory temporarily. B) They collect writes before sending to disk. C) They slow I/O. D) They remove data permanently.