Computer and Programming Foundations: Files, Exception Handling, and Modules

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/34

flashcard set

Earn XP

Description and Tags

Comprehensive review flashcards covering File I/O, Exception Handling, and Modules/Packages based on Computer Foundations lecture material.

35 Terms

1
New cards

Why is it necessary to store data in files rather than relying solely on variables in RAM?

Data stored in variables in RAM disappears once the program stops running; saving data in a file allows it to reside in permanent storage and be retrieved later.

2
New cards

What is the difference between an input file and an output file?

An input file is a file from which data is read (copied from the file into RAM variables), whereas an output file is a file to which data is written (copied from RAM variables to permanent storage).

3
New cards

What are the three mandatory steps when working with an I/O file in a program?

  1. Open the file (creates a connection between the file and program); 2. Process the file (read data from or write data to the file); 3. Close the file (disconnects the file from the program).
4
New cards

What is a file extension, and what role does it serve?

A file extension is a short sequence of characters preceded by a period at the end of a filename (such as .py, .cpp, .dat, .txt) that indicates the type of data stored in the file.

5
New cards

What are the standard path separators for Windows and Mac operating systems?

Windows uses a backslash (\\backslash), while Mac uses a forward slash (//).

6
New cards

What are the effects of the file modes 'r', 'w', 'a', and 'r+' when used in the open() function?

'r' opens for reading only (default mode); 'w' opens for writing only and overwrites any existing content; 'a' opens for writing only with appending; 'r+' is an update mode allowing both reading and writing simultaneously.

7
New cards

How do read(), readlines(), and readline() differ in how they retrieve file content?

read() reads the entire file as a single string; readlines() reads the entire file into a list of strings where each element represents a single line ending in \n; readline() reads one line at a time and returns it as a string.

8
New cards

Why can read() and readlines() only be used once without closing and reopening a file?

Both methods read file content sequentially until the end of the file (EOF) is reached.

9
New cards

What conversion must occur when reading numeric values from a file in Python, and why?

Python file reading methods read all content as strings; to use the data mathematically, they must be converted to numeric types using the int() or float() functions.

10
New cards

What conversion is required when writing numeric values to a file using the write() method?

The write() method only accepts strings, so numeric values (integers or floating-point numbers) must be converted to string format using the str() function.

11
New cards

What error occurs if Python attempts to open a file for reading that does not exist?

FileNotFoundError (Errno 2: No such file or directory).

12
New cards

What error is raised when attempting to read a non-plain-text file (such as an image) with readlines()?

UnicodeDecodeError (e.g., 'utf-8' codec can't decode byte).

13
New cards

What are the functions of os.path.join() and os.path.sep in Python's os module?

os.path.join() concatenates arguments using the correct OS path separator to ensure portability; os.path.sep stores the specific separator string used by the operating system currently in use.

14
New cards

What does os.path.split(aPath) return?

It splits a path into a 2-item tuple (head, tail), where tail is the last token in the path and head is everything else.

15
New cards

How do os.path.exists(aPath) and os.path.isfile(aPath) differ?

os.path.exists(aPath) returns True if the specified path exists; os.path.isfile(aPath) returns True only if the specified path exists and is an actual file (returning False if it is a directory).

16
New cards

What does the os.listdir(path) function return?

It returns a list containing the base filenames and suffixes of all files in the specified input directory.

17
New cards

What is the primary advantage of using a 'with' statement when opening files in Python?

The with statement automatically closes the file once the block of statements finishes executing, guaranteeing the file is closed even without calling close().

18
New cards

What is an exception in Python?

An error that occurs during program execution.

19
New cards

How does the try / except construct handle exceptions?

Code that may potentially produce an error is placed in the try block; if an exception occurs, remaining statements in the try block are skipped and execution shifts to the except block to handle the error gracefully without crashing.

20
New cards

According to the lecture, what specific circumstance causes a TypeError?

An operation or function is applied to an object of inappropriate type.

21
New cards

According to the lecture, what specific circumstance causes a NameError?

A variable name was used that doesn't exit [exist].

22
New cards

According to the lecture, what specific circumstance causes a ValueError?

A type conversion failed.

23
New cards

According to the lecture, what specific circumstance causes a ZeroDivisionError?

Division by zero attempted.

24
New cards

How can multiple exception types be handled by a single exception handler in Python?

By listing the exception types inside a tuple within the except clause (e.g., except (exceptiontype1, exceptiontype2):).

25
New cards

What occurs when a program executes a raise statement?

It causes an immediate exit from the try block and triggers the execution of the appropriate exception handler.

26
New cards

What happens if an exception is raised within a function but not handled inside that function?

The function immediately exits, and the calling function is checked for an exception handler, continuing up the function call hierarchy until a handler is found or the program terminates.

27
New cards

Under what conditions does the finally clause execute in a try / except construct?

The finally clause always executes as the last code before the try block finishes: if no exception occurs, if an exception is handled, if an unhandled exception occurs (before re-raising), or if a break, continue, or return statement exits the try block.

28
New cards

What is the technical difference between a Python script and a Python module?

A script is code saved in a .py file and executed directly by the interpreter; a module is a file containing Python code meant to be imported and used by scripts, other modules, or the interactive interpreter.

29
New cards

What Python construct ensures that specific code is executed only when the file is run as a script and not when imported as a module?

if name == "main":

30
New cards

What is the difference between 'import moduleName' and 'from moduleName import featureName'?

'import moduleName' imports the module and requires accessing its contents via dot notation (moduleName.feature); 'from moduleName import featureName' imports the specific feature so it can be called directly without dot notation.

31
New cards

What is a package in Python, and how is it imported?

A package is a directory of modules that, when imported using the directory name, provides access to all modules stored within it.

32
New cards

What file must be present inside a directory for Python to treat it as a package?

A file named init.py (which is often empty, but may contain package initialization code).

33
New cards
<p>Based on the package hierarchy diagram shown below, what subdirectories are grouped under the top-level 'game' package, and what files do they contain?</p>

Based on the package hierarchy diagram shown below, what subdirectories are grouped under the top-level 'game' package, and what files do they contain?

The package contains two subdirectories: 'sound' (containing music.py, effects.py, and speech.py) and 'graphics' (containing models.py, textures.py, and terrain.py).

34
New cards

What are the capabilities of the Standard Library modules csv, zipfile, and SimpleHTTPServer?

csv manipulates (reads/writes) CSV files; zipfile creates and reads .zip archive files; SimpleHTTPServer provides a complete, working Web server.

35
New cards

What do the random(), randint(low, high), and choice(stringList) functions in Python's random module do?

random() returns a floating-point number between 00 and 11 (specifically between 00 and 0.99990.9999); randint(low, high) generates a random integer between low and high (inclusive); choice(stringList) accepts a list of strings and picks a random word from it.