Unit 6 subjective questions Files and Exceptions; Regular Expressions
INT108 — Python Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define a text file. Explain how Python represents and processes text-file data.
Model answer
A text file stores information as a sequence of readable characters. Examples include
.txt,.csv,.html, and Python source files.Python processes a text file as follows:
- The file is opened using the
open()function. - Its contents are decoded into Python strings using a character encoding such as UTF-8.
- Data can be read, written, or appended depending on the selected file mode.
- A newline character, represented by
\n, generally separates lines. - The file should be closed after use to release operating-system resources.
Example:
Pythonwith open("notes.txt", "r", encoding="utf-8") as file: content = file.read() print(content)The
withstatement automatically closes the file when the block finishes, even if an error occurs. - The file is opened using the
-
Question 2 of 20
Explain the syntax and purpose of Python's
open()function. Describe the commonly used file modes.Model answer
The
open()function creates a file object through which a program can access a file.Syntax:
Pythonfile_object = open(file_name, mode, encoding="utf-8")Important file modes are:
"r": Opens a file for reading. It raisesFileNotFoundErrorif the file does not exist."w": Opens a file for writing. It creates a new file or erases the existing contents."a": Opens a file for appending. New data is added at the end."x": Creates a new file and raisesFileExistsErrorif it already exists."b": Selects binary mode, as in"rb"or"wb"."t": Selects text mode and is the default."+": Allows both reading and writing, as in"r+".
Using
with open(...) as file:is preferred because it ensures that the file is closed automatically. -
Question 3 of 20
Describe the different methods used to read data from a text file in Python. Compare
read(),readline(), andreadlines().Model answer
Python provides several methods for reading text files:
read()reads the entire file as one string. An optional argument limits the number of characters read.readline()reads one line at a time. It usually retains the ending newline character.readlines()reads all lines and returns them as a list of strings.- Iterating directly over the file object reads one line at a time and is memory-efficient.
Example:
Pythonwith open("data.txt", "r", encoding="utf-8") as file: for line in file: print(line.strip())Comparison:
read()is convenient for small files but may consume significant memory for large files.readline()is useful when processing lines individually under explicit control.readlines()is useful when a list of all lines is required, but it also loads the complete file into memory.- Direct iteration is generally the best choice for processing a large text file line by line.
-
Question 4 of 20
Explain how variables of different data types can be written to a text file. Why is conversion sometimes required?
Model answer
The
write()method expects a string argument. Therefore, values such as integers, floating-point numbers, lists, and Boolean values must be converted to strings before they are written to a text file.Example:
Pythonname = "Asha" age = 20 average = 87.5 with open("student.txt", "w", encoding="utf-8") as file: file.write(name + "\n") file.write(str(age) + "\n") file.write(f"{average}\n")Important points:
str(value)converts a value to its string representation.- Formatted string literals provide a readable way to combine labels and values.
- Separators such as commas, spaces, or newline characters should be added explicitly.
- When data is read back from a text file, it is returned as text and may need conversion using functions such as
int()orfloat().
For complex Python objects, serialization methods such as pickling may be more appropriate.
-
Question 5 of 20
Distinguish between writing and appending to a file. Illustrate the difference with Python code.
Model answer
Writing and appending differ in how they treat existing file contents.
- Write mode
"w"creates the file if necessary and truncates an existing file before writing. - Append mode
"a"creates the file if necessary but preserves existing data and adds new content at the end.
Example of writing:
Pythonwith open("log.txt", "w", encoding="utf-8") as file: file.write("Program started\n")If
log.txtalready contains data, that data is removed.Example of appending:
Pythonwith open("log.txt", "a", encoding="utf-8") as file: file.write("Program completed\n")The second operation retains
Program startedand adds the new line after it. Write mode is suitable when a file must be replaced, whereas append mode is suitable for logs, histories, and cumulative records. - Write mode
-
-
Question 6 of 20
Develop a Python program that copies a text file while numbering its lines. Explain how the program handles resources and errors.
Model answer
A program can read the source file line by line and write each line to the destination with a line number.
Pythontry: with open("source.txt", "r", encoding="utf-8") as source, \ open("numbered.txt", "w", encoding="utf-8") as target: for number, line in enumerate(source, start=1): target.write(f"{number}: {line}") except FileNotFoundError: print("The source file was not found.") except OSError as error: print(f"File operation failed: {error}") else: print("The file was copied successfully.")Explanation:
enumerate(..., start=1)supplies consecutive line numbers.- Direct iteration avoids loading the entire source file into memory.
- The two context managers automatically close both files.
FileNotFoundErrorhandles a missing source file.OSErrorhandles other input/output failures.- The
elseblock runs only when the copying operation completes without an exception.
-
Question 7 of 20
Explain how Python programs work with directories and file paths using the
pathlibmodule.Model answer
The
pathlibmodule represents paths as objects and provides platform-independent operations for files and directories.Pythonfrom pathlib import Path folder = Path("reports") folder.mkdir(parents=True, exist_ok=True) file_path = folder / "summary.txt" file_path.write_text("Monthly summary\n", encoding="utf-8") for item in folder.iterdir(): print(item.name)Common operations include:
Path.cwd()returns the current working directory.Path.home()returns the user's home directory.path.exists()checks whether a path exists.path.is_file()andpath.is_dir()identify the path type.mkdir()creates a directory.iterdir()lists directory contents.- The
/operator joins path components. unlink()removes a file, whilermdir()removes an empty directory.
Using
pathlibavoids manually selecting operating-system-specific path separators. -
Question 8 of 20
What is pickling in Python? Explain how an object is serialized and deserialized.
Model answer
Pickling is the process of converting a Python object into a binary byte stream so that it can be stored or transmitted. Unpickling reconstructs the object from that byte stream.
Pythonimport pickle student = {"name": "Ravi", "marks": [78, 84, 91]} with open("student.pkl", "wb") as file: pickle.dump(student, file) with open("student.pkl", "rb") as file: restored_student = pickle.load(file) print(restored_student)Key points:
pickle.dump()serializes an object into a binary file.pickle.load()deserializes an object from a binary file.- Binary modes
"wb"and"rb"are required. - Pickling can preserve structures such as lists, dictionaries, sets, and user-defined objects.
- Pickle data is Python-specific and is not intended as a language-independent exchange format.
-
Question 9 of 20
Compare pickling with storing data in a text file. Include the advantages, limitations, and security concerns of pickling.
Model answer
Text files:
- Store readable characters.
- Can be inspected and edited using ordinary text editors.
- Are generally portable between programming languages.
- Require explicit parsing and type conversion when complex data is restored.
Pickle files:
- Store serialized Python objects in binary form.
- Preserve many Python data types and nested structures automatically.
- Are usually more convenient for temporary Python-specific persistence.
- Are not human-readable and may be incompatible across applications or class definitions.
Security concern:
Unpickling untrusted data is dangerous because a malicious pickle can execute arbitrary code during loading. A program must only call
pickle.load()on data from a trusted source.For interoperable or untrusted structured data, formats such as JSON are generally safer. Pickle is appropriate when Python-specific objects must be restored and the producer of the file is trusted.
-
Question 10 of 20
What is an exception? Explain how a
ZeroDivisionErroroccurs and how it can be handled.Model answer
An exception is an object representing an error or unusual condition detected while a program is running. If it is not handled, normal execution stops and Python displays a traceback.
ZeroDivisionErroroccurs when a number is divided by zero or when a modulo operation uses zero as the divisor.Pythontry: numerator = float(input("Enter numerator: ")) denominator = float(input("Enter denominator: ")) result = numerator / denominator except ZeroDivisionError: print("The denominator cannot be zero.") else: print(f"Result: {result}")If the denominator is zero, Python transfers control from the
tryblock to the matchingexceptblock. The program therefore handles the problem gracefully instead of terminating unexpectedly. Input-conversion errors could be handled separately usingexcept ValueError:. -
Question 11 of 20
Describe the structure and execution flow of a
try-exceptstatement. How can multiple exception types be handled?Model answer
A
try-exceptstatement separates code that may fail from code that responds to specific failures.Pythontry: value = int(input("Enter an integer: ")) result = 100 / value except ValueError: print("The input is not a valid integer.") except ZeroDivisionError: print("Zero is not allowed.")Execution proceeds as follows:
- Python executes the statements in the
tryblock. - If no exception occurs, all
exceptblocks are skipped. - If an exception occurs, the rest of the
tryblock is skipped. - Python searches for the first compatible
exceptclause. - The matching handler runs, and execution then continues after the complete statement.
Related exceptions may be grouped as
except (TypeError, ValueError):. Separate handlers are preferable when each error requires a different response. Specific handlers should appear before broad handlers such asexcept Exception:. - Python executes the statements in the
-
Question 12 of 20
Explain the purpose of the
elseblock in exception handling. How is it different from code placed directly after atry-exceptstatement?Model answer
The
elseblock executes only when thetryblock finishes without raising an exception.Pythontry: number = int(input("Enter a number: ")) reciprocal = 1 / number except ValueError: print("Invalid number.") except ZeroDivisionError: print("Reciprocal of zero is undefined.") else: print(f"Reciprocal: {reciprocal}")The
elseblock is useful because it keeps successful follow-up operations outside the protectedtryblock. This prevents the handlers from accidentally catching exceptions raised by code that does not need protection.Code after the entire
try-exceptstatement normally runs whether an exception was handled or no exception occurred. By contrast, code inelseruns only on the no-exception path. Thus,elseclearly expresses that an operation depends on successful completion of thetryblock. -
Question 13 of 20
Explain
FileNotFoundErrorand write a program that handles it while reading a file.Model answer
FileNotFoundErroris raised when a program attempts an operation requiring a file or directory that does not exist. A common example is opening a missing file in read mode.Pythonfile_name = input("Enter the file name: ") try: with open(file_name, "r", encoding="utf-8") as file: contents = file.read() except FileNotFoundError: print(f"The file {file_name!r} does not exist.") except PermissionError: print("Permission to read the file was denied.") else: print(contents)The first handler gives a meaningful response when the path is missing. The second distinguishes a permission problem from a missing file. The
elseblock displays the contents only after successful reading, and the context manager closes the file automatically. -
Question 14 of 20
Design a robust Python function that divides two user-supplied values and records the result in a file. Handle likely input, arithmetic, and file exceptions.
Model answer
A robust solution should assign different responses to different failure categories.
Pythondef calculate_and_save(): try: first = float(input("Enter the dividend: ")) second = float(input("Enter the divisor: ")) result = first / second with open("result.txt", "w", encoding="utf-8") as file: file.write(f"{first} / {second} = {result}\n") except ValueError: print("Both inputs must be numeric.") except ZeroDivisionError: print("Division by zero is not permitted.") except OSError as error: print(f"The result could not be saved: {error}") else: print("The calculation was saved successfully.") calculate_and_save()Reasoning:
ValueErrorhandles invalid numeric input.ZeroDivisionErrorhandles a zero divisor.OSErrorcovers failures related to creating or writing the file.elseconfirms success only if every operation intrycompletes.- The
withstatement closes the output file even if writing fails.
-
Question 15 of 20
Define a regular expression. Explain the roles of literal characters, metacharacters, and raw strings in Python patterns.
Model answer
A regular expression, or regex, is a pattern that describes a set of strings. Python supplies regular-expression operations through the
remodule.- Literal characters match themselves. For example,
catmatches the exact sequencecat. - Metacharacters have special meanings. Common examples are
.,^,$,*,+,?,{},[],(),|, and\\. - A backslash introduces predefined classes or escapes a metacharacter. For example,
\drepresents a digit at the regex level. - Raw strings, written with an
rprefix, reduce conflicts between Python string escaping and regex escaping.
Example:
Pythonimport re pattern = r"^ID-\d{4}$" print(bool(re.match(pattern, "ID-2048")))The pattern requires the string to begin with
ID-, contain exactly four digits, and then end. - Literal characters match themselves. For example,
-
Question 16 of 20
Describe the major types of regular-expression elements: character classes, quantifiers, anchors, groups, and alternation. Give examples.
Model answer
Major regular-expression elements include:
- Character classes:
[abc]matches one listed character,[a-z]matches a lowercase letter,\dmatches a digit,\wmatches a word character, and\smatches whitespace. - Negated classes:
[^0-9]matches one character that is not a digit. - Quantifiers:
*means zero or more,+means one or more,?means zero or one, and{m,n}specifies a range of repetitions. - Anchors:
^matches the beginning and$matches the end of a string or line, depending on flags. - Groups:
(ab)+groupsabso that the complete sequence can repeat. Parentheses can also capture matched text. - Alternation:
cat|dogmatches eithercatordog. - Wildcard:
.normally matches any character except a newline.
For example,
r"^[A-Za-z][A-Za-z0-9_]{2,11}$"describes an identifier of 3 to 12 permitted characters that starts with a letter. - Character classes:
-
Question 17 of 20
Explain the use of
re.match(). Compare it withre.search()andre.fullmatch().Model answer
re.match(pattern, string)attempts to match the pattern only at the beginning of the string. It returns a match object on success andNoneon failure.Pythonimport re result = re.match(r"[A-Z]+", "PYTHON 3") if result: print(result.group()) # PYTHON print(result.start()) # 0 print(result.end()) # 6 print(result.span()) # (0, 6)Comparison:
re.match()requires the match to start at position zero but does not require the entire string to match.re.search()scans the string and returns the first match found at any position.re.fullmatch()succeeds only when the complete string conforms to the pattern.
For complete input validation,
re.fullmatch()is often clearer.re.match()is appropriate when only a prefix must be checked, whilere.search()is suitable for locating a pattern within larger text. -
Question 18 of 20
Construct and explain regular expressions for validating an email address, a ten-digit mobile number, and a date in
DD-MM-YYYYformat.Model answer
Possible validation patterns are:
Email address:
Pythonemail_pattern = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"This requires a local part, an
@symbol, a domain, a dot, and an alphabetic suffix of at least two characters. It is useful for ordinary validation but does not implement every rule in the complete email standard.Ten-digit mobile number:
Pythonmobile_pattern = r"[6-9]\d{9}"This example requires exactly ten digits and restricts the first digit to the range 6 through 9.
Date:
Pythondate_pattern = r"(0[1-9]|[12]\d|3[01])-(0[1-9]|1[0-2])-\d{4}"This checks the broad format and numeric ranges for days and months. It does not reject impossible dates such as
31-02-2025.Each pattern should be passed to
re.fullmatch()so that extra leading or trailing text is rejected. Calendar-aware code should perform final semantic date validation. -
Question 19 of 20
Explain how regular expressions can be used in web scraping. State the steps involved and the main limitations of this approach.
Model answer
Web scraping involves downloading web content and extracting required information from it. A simple regex-based workflow is:
- Send an HTTP request to a permitted web page.
- Check that the response was successful.
- Obtain the HTML as text.
- Define a regular expression for a stable textual pattern.
- Use functions such as
re.findall()orre.finditer()to collect matches. - Clean, validate, and store the extracted values.
Regular expressions can be suitable for narrow tasks such as extracting consistently formatted email addresses, identifiers, or values from a simple controlled page.
However, HTML is hierarchical and may contain nested elements, varying whitespace, attributes in different orders, comments, scripts, and malformed markup. A regex can therefore break when the page structure changes. HTML parsers such as Beautiful Soup are generally more reliable for locating elements, while regex may still be used to validate or extract patterns from the resulting text. Scrapers must also respect site terms, access restrictions, rate limits, privacy, and
robots.txtguidance. -
Question 20 of 20
Write and explain a Python program that downloads a web page and extracts email-like strings using regular expressions. Include appropriate error handling.
Model answer
The following example uses the
requestslibrary to retrieve a page and a regular expression to locate email-like strings:Pythonimport re import requests url = "https://example.com/contact" email_pattern = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}" try: response = requests.get(url, timeout=10) response.raise_for_status() except requests.RequestException as error: print(f"Unable to retrieve the page: {error}") else: emails = sorted(set(re.findall(email_pattern, response.text))) if emails: for email in emails: print(email) else: print("No email addresses were found.")Explanation:
requests.get()downloads the resource and limits waiting time withtimeout.raise_for_status()converts unsuccessful HTTP responses into exceptions.RequestExceptionhandles network, timeout, and HTTP-related failures.re.findall()returns all non-overlapping matches.set()removes duplicates, andsorted()creates predictable output.- The pattern is intentionally practical rather than a complete implementation of every valid email-address rule.
The program should only be used where automated access is authorized. For complex HTML extraction, an HTML parser should be used before applying regex to the extracted text.
That's unit 6
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 6 of INT108 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 6 of INT108 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.