Unit 6: Files and Exceptions; Regular Expressions - Subjective Questions
INT108 — Python Programming • Practice Questions with Detailed Answers
20 questions
Define a text file. Explain how Python represents and processes text-file data.
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:
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)The with statement automatically closes the file when the block finishes, even if an error occurs.
Explain the syntax and purpose of Python's open() function. Describe the commonly used file modes.
The open() function creates a file object through which a program can access a file.
Syntax:
file_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.
Describe the different methods used to read data from a text file in Python. Compare read(), readline(), and readlines().
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:
with 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.
Explain how variables of different data types can be written to a text file. Why is conversion sometimes required?
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:
name = "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.
Distinguish between writing and appending to a file. Illustrate the difference with Python code.
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:
with open("log.txt", "w", encoding="utf-8") as file:
file.write("Program started\n")If log.txt already contains data, that data is removed.
Example of appending:
with open("log.txt", "a", encoding="utf-8") as file:
file.write("Program completed\n")The second operation retains Program started and 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.
Develop a Python program that copies a text file while numbering its lines. Explain how the program handles resources and errors.
A program can read the source file line by line and write each line to the destination with a line number.
try:
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.
Explain how Python programs work with directories and file paths using the pathlib module.
The pathlib module represents paths as objects and provides platform-independent operations for files and directories.
from 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 pathlib avoids manually selecting operating-system-specific path separators.
What is pickling in Python? Explain how an object is serialized and deserialized.
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.
import 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.
Compare pickling with storing data in a text file. Include the advantages, limitations, and security concerns of pickling.
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.
What is an exception? Explain how a ZeroDivisionError occurs and how it can be handled.
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.
ZeroDivisionError occurs when a number is divided by zero or when a modulo operation uses zero as the divisor.
try:
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 try block to the matching except block. The program therefore handles the problem gracefully instead of terminating unexpectedly. Input-conversion errors could be handled separately using except ValueError:.
Describe the structure and execution flow of a try-except statement. How can multiple exception types be handled?
A try-except statement separates code that may fail from code that responds to specific failures.
try:
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 as except Exception:.
Explain the purpose of the else block in exception handling. How is it different from code placed directly after a try-except statement?
The else block executes only when the try block finishes without raising an exception.
try:
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 else block is useful because it keeps successful follow-up operations outside the protected try block. This prevents the handlers from accidentally catching exceptions raised by code that does not need protection.
Code after the entire try-except statement normally runs whether an exception was handled or no exception occurred. By contrast, code in else runs only on the no-exception path. Thus, else clearly expresses that an operation depends on successful completion of the try block.
Explain FileNotFoundError and write a program that handles it while reading a file.
FileNotFoundError is 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.
file_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 else block displays the contents only after successful reading, and the context manager closes the file automatically.
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.
A robust solution should assign different responses to different failure categories.
def 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.
Define a regular expression. Explain the roles of literal characters, metacharacters, and raw strings in Python patterns.
A regular expression, or regex, is a pattern that describes a set of strings. Python supplies regular-expression operations through the re module.
- 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:
import 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.
Describe the major types of regular-expression elements: character classes, quantifiers, anchors, groups, and alternation. Give examples.
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.
Explain the use of re.match(). Compare it with re.search() and re.fullmatch().
re.match(pattern, string) attempts to match the pattern only at the beginning of the string. It returns a match object on success and None on failure.
import 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, while re.search() is suitable for locating a pattern within larger text.
Construct and explain regular expressions for validating an email address, a ten-digit mobile number, and a date in DD-MM-YYYY format.
Possible validation patterns are:
Email address:
email_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:
mobile_pattern = r"[6-9]\d{9}"This example requires exactly ten digits and restricts the first digit to the range 6 through 9.
Date:
date_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.
Explain how regular expressions can be used in web scraping. State the steps involved and the main limitations of this approach.
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.txt guidance.
Write and explain a Python program that downloads a web page and extracts email-like strings using regular expressions. Include appropriate error handling.
The following example uses the requests library to retrieve a page and a regular expression to locate email-like strings:
import 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.
Define a text file. Explain how Python represents and processes text-file data.
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:
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)The with statement automatically closes the file when the block finishes, even if an error occurs.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. 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. Chip in only if it was worth it. What it pays for →