Unit 6: File Handling, Data Loading, and Visualization - Practice Quiz
1 Which Python function is commonly used to open a file?
2 Which file method reads the entire contents of a text file?
3 Which file mode is used to write new content to a file?
4 Which method writes a string to an open file?
5 Which Python module provides functions for working with folders and file paths?
6
Which function checks whether a path exists when using the os.path module?
7 Which file mode opens a file for reading binary data?
8 Which type represents binary data in Python?
9 Which Python module is commonly used to access command-line arguments?
10
Where are command-line arguments stored in Python when using the sys module?
11
What is a main advantage of using the with statement when working with files?
12
Which statement correctly opens data.txt for reading using a context manager?
13 What does CSV stand for?
14 Which Python module is designed for reading and writing CSV files?
15 Which Python library is commonly used to send HTTP requests and download web resources?
16 What does a URL identify?
17 Which pandas function loads a CSV file into a DataFrame?
18 What does filtering a DataFrame usually do?
19 Which pair of libraries is commonly used for data visualization in Python?
20 Which type of plot is useful for showing change over time?
21
What is printed by the following code if data.txt contains three lines, each ending with a newline character?
with open("data.txt", "r") as file:
lines = file.readlines()
print(len(lines))
22
A program should add a new log entry to events.log without deleting existing entries. Which file mode should be used?
"w"
"a"
"r"
"x"
23 Which statement correctly checks whether a path refers to an existing directory?
os.path.folder(path)
os.path.isdir(path)
os.path.exists(file)
os.path.isfile(path)
24
Why should an image file usually be opened with mode "rb" rather than "r"?
25
Suppose a script is run as python report.py input.csv. Which expression gives the string input.csv?
sys.file[1]
sys.argv[2]
sys.argv[0]
sys.argv[1]
26
What is the main advantage of using the following structure?
with open("notes.txt") as file:
text = file.read()
27 A CSV file contains a header row and numeric values. Which pandas statement loads it and treats the first row as column names?
pd.read_text("data.csv", header=0)
pd.read_csv("data.csv", header=0)
pd.read_csv("data.csv", index_col=0)
pd.read_csv("data.csv", header=None)
28 Which code correctly downloads the contents of a URL and saves them to a local file in binary mode?
response = requests.get(url); open("file.bin", "wb").write(response.content)
open(url, "wb").write(requests.get(url).text)
requests.get(url).save("file.bin")
urllib.read(url, "file.bin")
29
After executing df = pd.read_csv("scores.csv"), which expression returns the first five rows of the DataFrame?
df.sample(5, first=True)
df.rows(0, 5)
df.head()
df.first(5)
30
Given a DataFrame df with a numeric column named age, which expression selects rows for people aged at least 18?
df[df["age"] >= 18]
df[df["age"] > 18]
df["age" >= 18]
df.filter(age >= 18)
31 Which statement best describes a typical difference between Matplotlib and Seaborn?
32 Which plot is most appropriate for showing how a city's temperature changes over 30 consecutive days?
33 A DataFrame contains one row per department and a column containing total sales. Which chart best compares sales among departments?
34
What does changing bins=5 to bins=20 in a histogram generally do?
35 A scatter plot shows points forming a strong upward pattern from left to right. What does this most directly suggest?
36 Which expression reads all text from a file and removes leading and trailing whitespace from the entire result?
file.read().strip()
read(file).whitespace()
file.readlines().trim()
file.strip().read()
37
What happens when a file is opened with mode "w" and the file already exists?
38
Which code creates a directory named output only if it does not already exist?
os.path.create("output")
os.create_dir("output", safe=True)
os.makedirs("output", exist_ok=True)
os.mkdir("output", exist_ok=True)
39
A CSV column named price is loaded as strings because some entries contain currency symbols. Which operation is most appropriate before calculating the mean?
value_counts() as the mean
40
Which pandas expression selects only the name and score columns for rows where score is greater than 75?
df[df["score"]]["name", "score"] > 75
df["name", "score", df["score"] > 75]
df.select("name", "score", where=75)
df[["name", "score"]][df["score"] > 75]
41 A UTF-8 text file contains a multibyte character split across two byte chunks. Which approach reliably decodes the complete stream without risking a decoding error at the chunk boundary?
chunk.decode("utf-8")
errors="replace" before processing
errors="ignore" and join the results
42 A program must update a large configuration file so that a crash never leaves a partially written replacement visible. Which strategy provides the strongest basic atomicity guarantee on the same filesystem?
os.fsync() afterward
43
Why is Path("uploads") / user_supplied_name unsafe as a final destination when the name may contain .. components?
uploads after normalization
44
A binary file stores unsigned 16-bit integers in little-endian order. Which expression correctly interprets the first four bytes as two values using Python's struct module?
struct.unpack("<4H", data[:4])
struct.unpack("=2h", data[:4])
struct.unpack("<2H", data[:4])
struct.unpack(">2H", data[:4])
45
A command-line program accepts an input path that may begin with -. Which design most reliably prevents the path from being interpreted as an option?
input() after parsing all options
-- separator or use a named argument
argparse
46
What is the main reason with open(path) as f: is preferred over manually calling open() and close() around file operations?
47
A CSV field contains "Smith, Jane", and another field contains an embedded newline inside quotes. Which method correctly preserves both fields?
str.splitlines() followed by whitespace splitting
csv.reader with the file opened using newline=""
line.split(",")
48 A script downloads a large file over HTTP and must avoid silently accepting an error page returned with status code 404. Which sequence is most appropriate?
response.raise_for_status() before streaming the body
response.text and test whether it contains HTML
response.content and assume nonempty data means success
49
A dataset has a numeric column containing values such as "1,250", "—", and "980". Which loading strategy best preserves numeric analysis while treating the dash as missing?
50
In pandas, df contains a nullable integer column age. Which filter retains rows where age is at least 18 while excluding missing ages without relying on ambiguous Boolean NA behavior?
df[df["age"].ge(18).fillna(False)]
df[df["age"] >= 18]
df[df["age"].isna() | (df["age"] < 18)]
df.loc[df["age"].astype(str) >= "18"]
51 A Seaborn plot is created inside a loop, and each iteration adds another axes to the same figure. Which practice prevents accidental overlay or accumulation across iterations?
plt.figure() only after the loop has completed
sns.set_theme() before every plotting command
52 A time-series line plot appears to connect observations in a visually misleading order. What is the most direct correction when the timestamps are valid but unsorted?
53 A bar chart compares category totals, but one category has no observations and must still appear with a zero-height bar. Which preparation is most appropriate?
54 Two histograms are compared using different bin edges. Why can their bar heights not be compared directly, even if both use the same y-axis label?
55 A scatter plot contains one extremely large outlier that compresses nearly all other points into a small region. Which change improves visibility while preserving the outlier?
56 A text file may use either UTF-8 or a platform-specific encoding, and decoding errors must not silently corrupt data. Which policy is safest for a data-processing pipeline?
errors="ignore" so processing never stops
57 A program writes text intended to be consumed consistently on Windows and Linux. Which choice best avoids accidental platform-dependent newline transformations?
print() and rely on the operating system default
newline behavior when opening the text file
58 A file contains a sequence of raw 32-bit floating-point values, and performance matters when analyzing the entire file. Which approach avoids unnecessary Python-level unpacking loops?
float() repeatedly
numpy.fromfile with the correct dtype and byte order
59 A dataset is split into training and test files, but preprocessing includes computing the mean used for standardization. Where should that mean be computed?
60
A pandas DataFrame has duplicate timestamps for several sensors. The requirement is to retain the latest record per sensor and timestamp according to an updated_at column. Which operation expresses this reliably?
updated_at, then drop duplicates on sensor and timestamp, keeping the last
updated_at
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 →