Unit 6: File Handling, Data Loading, and Visualization - Practice Quiz

CSR101 — Python Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which Python function is commonly used to open a file?

Reading files Easy
A. read()
B. file()
C. open()
D. load()

2 Which file method reads the entire contents of a text file?

Reading files Easy
A. append()
B. read()
C. write()
D. close()

3 Which file mode is used to write new content to a file?

Writing files Easy
A. x
B. rb
C. w
D. r

4 Which method writes a string to an open file?

Writing files Easy
A. send()
B. put()
C. insert()
D. write()

5 Which Python module provides functions for working with folders and file paths?

Interacting with file systems Easy
A. turtle
B. random
C. math
D. os

6 Which function checks whether a path exists when using the os.path module?

Interacting with file systems Easy
A. os.path.exists()
B. os.path.valid()
C. os.path.find()
D. os.path.check()

7 Which file mode opens a file for reading binary data?

Binary data Easy
A. rt
B. r
C. rb
D. w

8 Which type represents binary data in Python?

Binary data Easy
A. float
B. str
C. dict
D. bytes

9 Which Python module is commonly used to access command-line arguments?

Command-line arguments and files Easy
A. time
B. re
C. csv
D. sys

10 Where are command-line arguments stored in Python when using the sys module?

Command-line arguments and files Easy
A. sys.inputs
B. sys.command
C. sys.args
D. sys.argv

11 What is a main advantage of using the with statement when working with files?

with statement Easy
A. It sorts the file contents
B. It downloads the file automatically
C. It converts files to CSV
D. It closes the file automatically

12 Which statement correctly opens data.txt for reading using a context manager?

with statement Easy
A. using open("data.txt") file:
B. with read("data.txt") as file:
C. with open("data.txt", "r") as file:
D. open with "data.txt" as file:

13 What does CSV stand for?

Comma-separated values files Easy
A. Computer-Saved Values
B. Comma-Separated Values
C. Common System Variables
D. Column Storage Version

14 Which Python module is designed for reading and writing CSV files?

Comma-separated values files Easy
A. json
B. sqlite
C. html
D. csv

15 Which Python library is commonly used to send HTTP requests and download web resources?

Getting files from the Internet Easy
A. requests
B. decimal
C. statistics
D. calendar

16 What does a URL identify?

Getting files from the Internet Easy
A. A database column
B. A Python loop
C. A file compression type
D. A web resource location

17 Which pandas function loads a CSV file into a DataFrame?

Loading data Easy
A. pd.import_data()
B. pd.open_csv()
C. pd.read_csv()
D. pd.load_table()

18 What does filtering a DataFrame usually do?

Selecting and filtering Easy
A. Changes numbers into images
B. Deletes every column
C. Selects rows meeting a condition
D. Downloads a new dataset

19 Which pair of libraries is commonly used for data visualization in Python?

Visualizing data with Matplotlib and Seaborn Easy
A. Flask and Django
B. NumPy and pathlib
C. Tkinter and unittest
D. Matplotlib and Seaborn

20 Which type of plot is useful for showing change over time?

Line plots Easy
A. Box-only plot
B. Histogram
C. Pie chart
D. Line plot

21 What is printed by the following code if data.txt contains three lines, each ending with a newline character?

PYTHON
with open("data.txt", "r") as file:
    lines = file.readlines()
print(len(lines))

Reading files Medium
A. The number of words in the file
B. The number of newline characters plus one
C. The number of lines in the file
D. The number of characters in the file

22 A program should add a new log entry to events.log without deleting existing entries. Which file mode should be used?

Writing files Medium
A. "w"
B. "a"
C. "r"
D. "x"

23 Which statement correctly checks whether a path refers to an existing directory?

Interacting with file systems Medium
A. os.path.folder(path)
B. os.path.isdir(path)
C. os.path.exists(file)
D. os.path.isfile(path)

24 Why should an image file usually be opened with mode "rb" rather than "r"?

Binary data Medium
A. It reads the file as raw bytes
B. It prevents the file from being closed
C. It automatically compresses the image
D. It converts the image into text

25 Suppose a script is run as python report.py input.csv. Which expression gives the string input.csv?

Command-line arguments and files Medium
A. sys.file[1]
B. sys.argv[2]
C. sys.argv[0]
D. sys.argv[1]

26 What is the main advantage of using the following structure?

PYTHON
with open("notes.txt") as file:
    text = file.read()

with statement Medium
A. The file can only be read once
B. The file is automatically duplicated
C. The file is automatically encrypted
D. The file is automatically closed

27 A CSV file contains a header row and numeric values. Which pandas statement loads it and treats the first row as column names?

Comma-separated values files Medium
A. pd.read_text("data.csv", header=0)
B. pd.read_csv("data.csv", header=0)
C. pd.read_csv("data.csv", index_col=0)
D. 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?

Getting files from the Internet Medium
A. response = requests.get(url); open("file.bin", "wb").write(response.content)
B. open(url, "wb").write(requests.get(url).text)
C. requests.get(url).save("file.bin")
D. urllib.read(url, "file.bin")

29 After executing df = pd.read_csv("scores.csv"), which expression returns the first five rows of the DataFrame?

Loading data Medium
A. df.sample(5, first=True)
B. df.rows(0, 5)
C. df.head()
D. df.first(5)

30 Given a DataFrame df with a numeric column named age, which expression selects rows for people aged at least 18?

Selecting and filtering Medium
A. df[df["age"] >= 18]
B. df[df["age"] > 18]
C. df["age" >= 18]
D. df.filter(age >= 18)

31 Which statement best describes a typical difference between Matplotlib and Seaborn?

Visualizing data with Matplotlib and Seaborn Medium
A. Matplotlib requires a database connection
B. Seaborn cannot create statistical plots
C. Matplotlib works only with image files
D. Seaborn provides higher-level statistical visualizations

32 Which plot is most appropriate for showing how a city's temperature changes over 30 consecutive days?

Line plots Medium
A. A scatter plot with no ordered axis
B. A line plot with day on the x-axis
C. A histogram with temperature labels
D. A pie chart with day as categories

33 A DataFrame contains one row per department and a column containing total sales. Which chart best compares sales among departments?

Bar charts Medium
A. A scatter plot using one point only
B. A line chart with departments as continuous values
C. A histogram of department names
D. A bar chart with departments as categories

34 What does changing bins=5 to bins=20 in a histogram generally do?

Histograms Medium
A. It changes the sample size
B. It removes all extreme values
C. It creates narrower value intervals
D. It converts counts into percentages

35 A scatter plot shows points forming a strong upward pattern from left to right. What does this most directly suggest?

Scatter plots Medium
A. No relationship between variables
B. That both variables are categorical
C. A strong positive association
D. A guaranteed causal relationship

36 Which expression reads all text from a file and removes leading and trailing whitespace from the entire result?

Reading files Medium
A. file.read().strip()
B. read(file).whitespace()
C. file.readlines().trim()
D. file.strip().read()

37 What happens when a file is opened with mode "w" and the file already exists?

Writing files Medium
A. An error always occurs before opening
B. The file is opened only for reading
C. New text is added after existing text
D. The existing contents are truncated

38 Which code creates a directory named output only if it does not already exist?

Interacting with file systems Medium
A. os.path.create("output")
B. os.create_dir("output", safe=True)
C. os.makedirs("output", exist_ok=True)
D. 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?

Comma-separated values files Medium
A. Rename the column without changing its values
B. Sort the strings alphabetically
C. Use value_counts() as the mean
D. Convert the values to numeric after removing symbols

40 Which pandas expression selects only the name and score columns for rows where score is greater than 75?

Selecting and filtering Medium
A. df[df["score"]]["name", "score"] > 75
B. df["name", "score", df["score"] > 75]
C. df.select("name", "score", where=75)
D. 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?

Reading files Hard
A. Decode each chunk independently with chunk.decode("utf-8")
B. Decode each chunk with errors="replace" before processing
C. Decode chunks with errors="ignore" and join the results
D. Concatenate all chunks and decode once after reading

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?

Writing files Hard
A. Write a temporary file, flush it, then replace the original
B. Write the changes directly and call os.fsync() afterward
C. Open the original in text mode and truncate it before writing
D. Open the original in append mode and write the changes

43 Why is Path("uploads") / user_supplied_name unsafe as a final destination when the name may contain .. components?

Interacting with file systems Hard
A. It prevents access to files on case-sensitive systems
B. It can resolve outside uploads after normalization
C. It silently changes all path separators to spaces
D. It always converts the path into an absolute path

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?

Binary data Hard
A. struct.unpack("<4H", data[:4])
B. struct.unpack("=2h", data[:4])
C. struct.unpack("<2H", data[:4])
D. 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?

Command-line arguments and files Hard
A. Read the path with input() after parsing all options
B. Remove every hyphen from the path before opening it
C. Require the path after a -- separator or use a named argument
D. Convert the path to uppercase before passing it to argparse

46 What is the main reason with open(path) as f: is preferred over manually calling open() and close() around file operations?

with statement Hard
A. It automatically converts binary data into Unicode text
B. It closes the resource even when the block raises an exception
C. It prevents every possible filesystem permission error
D. It guarantees that every read returns a complete line

47 A CSV field contains "Smith, Jane", and another field contains an embedded newline inside quotes. Which method correctly preserves both fields?

Comma-separated values files Hard
A. Replace commas with semicolons before splitting each line
B. Use str.splitlines() followed by whitespace splitting
C. Use csv.reader with the file opened using newline=""
D. Split each physical line with 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?

Getting files from the Internet Hard
A. Call response.raise_for_status() before streaming the body
B. Read response.text and test whether it contains HTML
C. Save the body first and inspect its filename afterward
D. Use 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?

Loading data Hard
A. Remove every comma from the entire raw file before loading
B. Specify the thousands separator and map the dash to missing
C. Convert the column to integers without handling special values
D. Load all values as strings and sort them lexicographically

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?

Selecting and filtering Hard
A. df[df["age"].ge(18).fillna(False)]
B. df[df["age"] >= 18]
C. df[df["age"].isna() | (df["age"] < 18)]
D. 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?

Visualizing data with Matplotlib and Seaborn Hard
A. Call plt.figure() only after the loop has completed
B. Increase the figure DPI after each iteration
C. Call sns.set_theme() before every plotting command
D. Create or clear the figure and axes for each iteration

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?

Line plots Hard
A. Use a logarithmic y-axis for the measurements
B. Replace the timestamps with their row indices
C. Sort the data by timestamp before plotting
D. Increase the line width to emphasize the trend

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?

Bar charts Hard
A. Reindex the aggregated counts with the complete category list and fill zeros
B. Replace the absent category with the mean of observed counts
C. Drop categories with missing counts before aggregation
D. Plot the raw observations and let the axis infer categories

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?

Histograms Hard
A. Histograms cannot display more than one dataset on a figure
B. The y-axis of every histogram must always be logarithmic
C. Different bins represent different intervals and possibly different widths
D. Different colors automatically normalize the distributions differently

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?

Scatter plots Hard
A. Use logarithmic scaling on the affected axis when appropriate
B. Replace the outlier with the column median
C. Delete the outlier before plotting
D. Increase marker transparency only on 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?

Reading files Hard
A. Always decode with ASCII and discard non-ASCII characters
B. Decode with the system default and assume it is stable
C. Use errors="ignore" so processing never stops
D. Declare or detect the encoding and fail explicitly when decoding is invalid

57 A program writes text intended to be consumed consistently on Windows and Linux. Which choice best avoids accidental platform-dependent newline transformations?

Writing files Hard
A. Write with print() and rely on the operating system default
B. Specify the desired newline behavior when opening the text file
C. Use binary mode and manually encode every character as ASCII
D. Replace every newline with a space before writing

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?

Binary data Hard
A. Convert each byte to hexadecimal before constructing floats
B. Read one byte at a time and call float() repeatedly
C. Use numpy.fromfile with the correct dtype and byte order
D. Decode the bytes as UTF-8 and split on whitespace

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?

Loading data Hard
A. From the training data only, then applied to both sets
B. Independently from each set to maximize local accuracy
C. From the test data because it is evaluated last
D. From the combined training and test data

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?

Selecting and filtering Hard
A. Sort by updated_at, then drop duplicates on sensor and timestamp, keeping the last
B. Sort by sensor name and assume the final row is the latest
C. Group only by timestamp and keep the first row in each group
D. Drop duplicates first, then sort the remaining rows by updated_at