WGU D522 PYTHON FOR IT AUTOMATION EXAM with
Questions and Answers/Plus a Rationale Updated 2026
A+/Instant Download PDF
EXAM COVERAGE
1. Python Syntax and Data Types
2. Control Structures and Functions
3. Object-Oriented Programming (OOP) in Python
4. Standard Libraries and Module Management
5. Interacting with the Operating System (OS)
6. Regular Expressions and Data Parsing
7. IT Infrastructure Automation and Scripting Ethics
1. An IT automation engineer is writing a script to process a continuous stream of system logs. The
script needs to store unique IP addresses encountered during the parsing process for fast
membership testing, while ensuring that duplicate entries are automatically discarded. Which
Python data structure should be utilized?
A. List
B. Tuple
C. Set
D. Dictionary
CORRECT ANSWER : C
Rationale: Sets are unordered collections of unique elements, which inherently prevent duplicate
entries and offer efficient $O(1)$ average time complexity for membership testing. Lists (A) and
, tuples (B) allow duplicates and require linear search times, whereas dictionaries (D) store key-
value pairs rather than standalone unique items.
2. A DevOps engineer is writing a configuration parsing script that reads a JSON file to retrieve
system properties. Which code snippet safely loads the JSON data and extracts the value
associated with the key "host" without risking unhandled runtime errors?
A. with open('config.json') as f: return f.read()['host']
B. with open('config.json') as f: return json.load(f)['host']
C. return json.loads('config.json')['host']
D. with open('config.json','w') as f: return json.dump(f)['host']
CORRECT ANSWER : B
Rationale: The json.load() method correctly parses a file-like object directly into a Python
dictionary, allowing safe key extraction. Option A attempts to index a string return value
directly, resulting in a TypeError. Option C passes a filename string instead of JSON text into
json.loads(). Option D opens the file in write mode ('w') instead of read mode.
3. An automation script needs to append a new status message ("DONE\n") to the end of an
existing log file named tasks.txt without erasing or overwriting any prior contents. Which file
handling implementation accomplishes this correctly?
A. open('tasks.txt','w').write("DONE\n")
B. with open('tasks.txt','a') as f: f.write("DONE\n")
C. open('tasks.txt','r').append("DONE\n")
D. with open('tasks.txt','x') as f: f.write("DONE\n")
CORRECT ANSWER : B
Rationale: Opening a file in append mode ('a') ensures that new write operations occur at the
end of the file without destroying historical data, and the context manager (with open...)
guarantees proper resource cleanup. Write mode ('w') overwrites the file, read mode ('r') does
not support writing, and exclusive creation mode ('x') fails if the file already exists.
4. A systems administrator needs to back up a complete directory tree containing server
configuration files to a secure backup directory, preserving subdirectories and metadata. Which
shutil function call achieves this operation efficiently?
A. shutil.copy('/home/user/data', '/home/user/data_backup')
, B. shutil.copytree('/home/user/data', '/home/user/data_backup')
C. shutil.move('/home/user/data', '/home/user/data_backup')
D. os.rename('/home/user/data', '/home/user/data_backup')
CORRECT ANSWER : B
Rationale: The shutil.copytree() function recursively copies an entire directory tree along with
all its files and subdirectories. shutil.copy() only handles single files, while shutil.move() and
os.rename() relocate or rename paths rather than duplicating entire directory structures.
5. An automation script must execute the shell command "df -h" to monitor disk space usage and
capture the standard output stream for log parsing. Which subprocess module method is best
suited for this task?
A. subprocess.run(["df", "-h"], capture_output=True, text=True,
check=True)
B. os.system("df -h")
C. subprocess.popen("DF -H")
D. subprocess.getstatus("df -h")
CORRECT ANSWER : A
Rationale: subprocess.run() is the modern, recommended approach in Python to execute shell
commands, allowing robust capture of standard output/error streams and exception handling via
check=True. os.system() only returns an exit code and lacks modern output capture controls.
6. A security script iterates through a log file containing multiple failed login attempts from various
IP addresses. The engineer needs to extract all matching IPv4 addresses using regular
expressions. Which module and compilation pattern correctly supports regular expression
matching in Python?
A. import regex followed by regex.findall()
B. import re followed by re.search() or re.findall()
C. import string followed by string.match()
D. import parse followed by parse.search()
CORRECT ANSWER : B
, Rationale: The built-in re module is the standard library tool for regular expression matching,
search, and pattern parsing in Python. Options A, C, and D either reference non-standard
packages or incorrect standard modules for regex operations.
7. A Python function is designed to process an incoming list of sensor metrics. If an invalid string is
encountered instead of an integer, the function must catch the exception, log a warning, and
continue processing remaining metrics. Which exception type should the script catch?
A. IndexError
B. KeyError
C. ValueError
D. TypeError
CORRECT ANSWER : C
Rationale: Converting invalid string literals to numeric values (such as int("abc")) triggers a
ValueError. IndexError handles sequence out-of-range bounds, KeyError handles missing
dictionary keys, and TypeError handles inappropriate object type applications.
8. An IT administrator is designing a custom Python class to manage remote server connections.
Which special method acts as the constructor class initializer, automatically executing whenever
a new server instance is instantiated?
A. __del__
B. __init__
C. __str__
D. __call__
CORRECT ANSWER : B
Rationale: The init method is the standard constructor in Python classes used to initialize an
object's attributes upon creation. del handles destruction, str manages string representation, and
call allows instances to be called like functions.
9. A script is designed to read lines from a large network trace file. To ensure system memory is
not overwhelmed by loading the entire multi-gigabyte file at once, which iteration approach is
most memory-efficient?
A. for line in open('network.log'): process(line)
Questions and Answers/Plus a Rationale Updated 2026
A+/Instant Download PDF
EXAM COVERAGE
1. Python Syntax and Data Types
2. Control Structures and Functions
3. Object-Oriented Programming (OOP) in Python
4. Standard Libraries and Module Management
5. Interacting with the Operating System (OS)
6. Regular Expressions and Data Parsing
7. IT Infrastructure Automation and Scripting Ethics
1. An IT automation engineer is writing a script to process a continuous stream of system logs. The
script needs to store unique IP addresses encountered during the parsing process for fast
membership testing, while ensuring that duplicate entries are automatically discarded. Which
Python data structure should be utilized?
A. List
B. Tuple
C. Set
D. Dictionary
CORRECT ANSWER : C
Rationale: Sets are unordered collections of unique elements, which inherently prevent duplicate
entries and offer efficient $O(1)$ average time complexity for membership testing. Lists (A) and
, tuples (B) allow duplicates and require linear search times, whereas dictionaries (D) store key-
value pairs rather than standalone unique items.
2. A DevOps engineer is writing a configuration parsing script that reads a JSON file to retrieve
system properties. Which code snippet safely loads the JSON data and extracts the value
associated with the key "host" without risking unhandled runtime errors?
A. with open('config.json') as f: return f.read()['host']
B. with open('config.json') as f: return json.load(f)['host']
C. return json.loads('config.json')['host']
D. with open('config.json','w') as f: return json.dump(f)['host']
CORRECT ANSWER : B
Rationale: The json.load() method correctly parses a file-like object directly into a Python
dictionary, allowing safe key extraction. Option A attempts to index a string return value
directly, resulting in a TypeError. Option C passes a filename string instead of JSON text into
json.loads(). Option D opens the file in write mode ('w') instead of read mode.
3. An automation script needs to append a new status message ("DONE\n") to the end of an
existing log file named tasks.txt without erasing or overwriting any prior contents. Which file
handling implementation accomplishes this correctly?
A. open('tasks.txt','w').write("DONE\n")
B. with open('tasks.txt','a') as f: f.write("DONE\n")
C. open('tasks.txt','r').append("DONE\n")
D. with open('tasks.txt','x') as f: f.write("DONE\n")
CORRECT ANSWER : B
Rationale: Opening a file in append mode ('a') ensures that new write operations occur at the
end of the file without destroying historical data, and the context manager (with open...)
guarantees proper resource cleanup. Write mode ('w') overwrites the file, read mode ('r') does
not support writing, and exclusive creation mode ('x') fails if the file already exists.
4. A systems administrator needs to back up a complete directory tree containing server
configuration files to a secure backup directory, preserving subdirectories and metadata. Which
shutil function call achieves this operation efficiently?
A. shutil.copy('/home/user/data', '/home/user/data_backup')
, B. shutil.copytree('/home/user/data', '/home/user/data_backup')
C. shutil.move('/home/user/data', '/home/user/data_backup')
D. os.rename('/home/user/data', '/home/user/data_backup')
CORRECT ANSWER : B
Rationale: The shutil.copytree() function recursively copies an entire directory tree along with
all its files and subdirectories. shutil.copy() only handles single files, while shutil.move() and
os.rename() relocate or rename paths rather than duplicating entire directory structures.
5. An automation script must execute the shell command "df -h" to monitor disk space usage and
capture the standard output stream for log parsing. Which subprocess module method is best
suited for this task?
A. subprocess.run(["df", "-h"], capture_output=True, text=True,
check=True)
B. os.system("df -h")
C. subprocess.popen("DF -H")
D. subprocess.getstatus("df -h")
CORRECT ANSWER : A
Rationale: subprocess.run() is the modern, recommended approach in Python to execute shell
commands, allowing robust capture of standard output/error streams and exception handling via
check=True. os.system() only returns an exit code and lacks modern output capture controls.
6. A security script iterates through a log file containing multiple failed login attempts from various
IP addresses. The engineer needs to extract all matching IPv4 addresses using regular
expressions. Which module and compilation pattern correctly supports regular expression
matching in Python?
A. import regex followed by regex.findall()
B. import re followed by re.search() or re.findall()
C. import string followed by string.match()
D. import parse followed by parse.search()
CORRECT ANSWER : B
, Rationale: The built-in re module is the standard library tool for regular expression matching,
search, and pattern parsing in Python. Options A, C, and D either reference non-standard
packages or incorrect standard modules for regex operations.
7. A Python function is designed to process an incoming list of sensor metrics. If an invalid string is
encountered instead of an integer, the function must catch the exception, log a warning, and
continue processing remaining metrics. Which exception type should the script catch?
A. IndexError
B. KeyError
C. ValueError
D. TypeError
CORRECT ANSWER : C
Rationale: Converting invalid string literals to numeric values (such as int("abc")) triggers a
ValueError. IndexError handles sequence out-of-range bounds, KeyError handles missing
dictionary keys, and TypeError handles inappropriate object type applications.
8. An IT administrator is designing a custom Python class to manage remote server connections.
Which special method acts as the constructor class initializer, automatically executing whenever
a new server instance is instantiated?
A. __del__
B. __init__
C. __str__
D. __call__
CORRECT ANSWER : B
Rationale: The init method is the standard constructor in Python classes used to initialize an
object's attributes upon creation. del handles destruction, str manages string representation, and
call allows instances to be called like functions.
9. A script is designed to read lines from a large network trace file. To ensure system memory is
not overwhelmed by loading the entire multi-gigabyte file at once, which iteration approach is
most memory-efficient?
A. for line in open('network.log'): process(line)