COMP560 W6 ZyCh7_Files

1) When reading a file in Python, you must specify two items:
A) a file name and mode

2) Before accessing a file, the program must:
A) open the file
3) After executing the following code snippet, what part is the file object?

infile = open("input.txt", "r")

 A) infile
 4) In the following code snippet, what does the "r" represent?

infile = open("input.txt", "r")

A) read
5) In the following code snippet, what does the "w" represent?

outfile = open("output.txt", "w")

A) write
6) In the following code snippet, what happens if the "output.txt" file does not exist?

outfile = open("output.txt", "w")

A) An empty file is created

7) In the following code snippet, what happens if the "output.txt" file already exists?

outfile = open("output.txt", "w")

A) The existing file is emptied

8) What method ensures that the output has been written to the disk file?
A) close()

9) The readline method reads text until an end of line symbol is encountered, how is an end of line character represented?
A) \n

10) What is returned when the readline method reaches the end of the file?
A) “”

11) When using the readline method, what data type is returned?
A) string
12) What method(s) can be used to write to a file?
A) write, print

13) What happens in the following code snippet?

infile = open("", "r")

A) a run-time error occurs because the file does not exist

14) Which of the following statements opens a text file for reading?
A) infile = open(“myfile.txt”, “r”)

15) What is the name of the file object variable in the following code segment?

a = open("b.txt", "r")

A) a

16) What happens when the following code segment executes if test.txt does not exist?

infile = open("test.txt", "r")

A) The program raises an exception
17) What happens when the following code segment executes if test.txt does not exist?

outfile = open("test.txt", "w")

A)  The file test.txt is created as a new empty file
18) Which statement is used to close the file object opened with the following statement?

infile = open("test.txt", "r")

A) infile.close()

19) Which statement(s) writes the sentence "Today is the first day of the rest of your life" to a file with one word on each line?
A) outfile.write(“Today \nis \nthe \nfirst \nday \nof \nthe \nrest \nof \nyour \nlife”)

20) Consider a program that wants to read a file from the absolute path c:\users\user1\states.dat. What statement allows you to read this file?
A) file = open(“c:\\users\\user1\\states.dat”, “r”)

21) What happens if you try to open a file for reading that doesn’t exist?
A) A run-time error occurs because the file does not exist.

22) Once a file has been opened, what method is used to read data from a file?
A) readline()

23) In the code snippet below, if the file contains the following words: apple, pear, and banana stored one per line, what would be the output?

infile = open("input.txt", "r")
for word in infile :
   word = word.rstrip()
   print(word)

A) apple
pear
banana

24) In the code snippet below, if the file contains the following words: Monday! Tuesday. Wednesday? stored one per line, what would be the output?

infile = open("input.txt", "r")
for word in infile :
   word = word.rstrip(".!\n") 
   print(word)

A) Monday
Tuesday
Wednesday?

25) Which of the following methods strips specified punctuation from the front or end of each string (s)?
A) s.strip(“.!?;:”)

26) Which statement below can be used to read data from a file one character at a time?
A) inputFile.read(1)

27) Given a text file quote.txt that contains this sentence:

Home computers are being called upon to perform many new
functions, including the consumption of homework formerly eaten by
the dog. ~Doug Larson

What is the result of this code snippet:

inputFile = open("quote.txt", "r")
  char = inputFile.read(1)
  while char != "" :
     print(char)
     char = inputFile.read(1)
  inputFile.close()

A) each character of the quote is printed on a separate line

28) Assume that outfile is a file object that has been opened for writing. Which of the following code segments stores

Hello
World

in the file?
A) outfile.write(“Hello\nWorld\n”)

29) The following code segment is supposed to read all of the lines from test.txt and save them in copy.txt.

infile = open("test.txt", "r")
outfile = open("copy.txt", "w")


line = infile.readline()
____________________
   outfile.write(line)
   line = infile.readline()


infile.close()
outfile.close()

Which line of code should be placed in the blank to achieve this goal?
A) while line != “” :

30) The following code segment is supposed to read and display the contents of a file. What problem does it have in its current form?

infile = open("test.txt", "r")


line = infile.readline()
while line != "" :
   print(line)
   line = infile.readline()


infile.close()

A) The program displays the contents of the file, but it is double spaced

31) The following program opens test.txt and displays its contents. If nothing is placed in the blank, then the contents of the file is displayed double spaced. What should be placed on the blank so that the contents of the file is displayed without the extra blank lines?

infile = open("test.txt", "r")


line = infile.readline()
while line != "" :
   ____________________
   print(line)
   line = infile.readline()


infile.close()

A) line = line.rstrip()

32) Consider the following code segment:

line = "hello world!"
parts = line.split()
print(parts)

What is displayed when this code segment runs?
A) [“hello”, “world!”]

33) Assume that a line has just been read from a file and stored in a variable named line. The line contains several words, each of which is separated by one or more spaces. Which of the following statements will store a list of all the words in wordList?
A) wordList = line.split()

34) What type of value is returned by the expression ord("A")?
A) Integer

35) Which of the following statements is NOT valid for reading from a file:
A) inputFile.readline(5)

36) Which of the following file operations is NOT valid for reading a binary file?
A) fileName = open(“input.dat”, “rw”)

37) What is wrong with the following code snippet that is supposed to print the contents of the file twice?

infile = open("input.txt", "r")
for sentence in infile :
   print(sentence)
      for sentence in infile :
         print(sentence)

A) Python cannot iterate over the file twice without closing and reopening the file

38) What is output by the following code segment when input.txt contains the following words: applepear, and banana stored one per line?

infile = open("input.txt", "r")
for word in infile :
   print(word)

A) apple


pear


banana

39) In the code snippet below, if the file contains the following words: Monday! Tuesday. Wednesday? stored one per line, what would be the output?

infile = open("input.txt", "r")
for word in infile :
   word = word.lstrip(".!")
   print(word)

A) Monday!


Tuesday.


Wednesday?

40) Which of the following methods provides a way to split the contents of the string sentence into a list of individual words?
A) sentence.split()

41) What will be stored in substrings after the following code snippet has run?

states = "Michigan,Maine,Minnesota,Montana,Mississippi"
substrings = states.split(",")

A) [“Michigan”, “Maine”, “Minnesota”, “Montana”, “Mississippi”]

42) What is stored in substrings after the following code snippet has run?

states = "Michigan,Maine,Minnesota,,Montana,Mississippi"
substrings = states.split(",")

A) [“Michigan”,”Maine”,”Minnesota”,””,”Montana”,”Mississippi”]

43) Given a text file quote.txt that contains this sentence:

Home computers are being called upon to perform many new
functions, including the consumption of homework formerly eaten by
the dog. ~Doug Larson

What will be printed by this code snippet?

letterCounts = [0] * 26
inputFile = open("quote.txt", "r")
char = inputFile.read(1)
while char != "" :
   char = char.upper() 
   if char >= "A" and char <= "Z" :
      code = ord(char) - ord("A")
      letterCounts[code] = letterCounts[code] + 1
   char = inputFile.read(1)
inputFile.close()
print(letterCounts[1])

A) 2

44) Suppose the input file contains a person’s last name and age on the same line separated by a space. Which statements extract this information correctly?
A) record = inputFile.readline()
data = record.split()
name = data[0].rstrip()
age = int(data[1])

45) Which of the following code segments will display all of the lines in the file object named infile, assuming that it has successfully been opened for reading?
A) for line in infile :
print(line)

46) What is wrong with the following code snippet:

file = open("lyrics.txt", "w")
line = file.readline()
words = line.split()
print(words) 
file.close()

A) The file has only been opened for writing, not reading.

47) Suppose an input file contains a grocery list. Each line contains the item name followed by its cost. The item name and cost are separated by a comma. Which statements extract this information correctly?
A) record = inputFile.readline()
data = record.split(“,”)
groceryItem = data[0].rstrip()
cost = float(data[1])

48) What portable file format is commonly used to export data from a spreadsheet so that it can be read and processed by a Python program?
A) Comma-Separated Values (CSV)

49) Consider the following code segment:

from csv import writer


outfile = open("newdata.csv", "w")  
csvWriter = writer(outfile)

What statement should be added to the end of this code segment so that it will write a row of values to the file?
A) csvWriter.writerow([1, 2, 3, 4])

50) Which statement imports all of the functions in Python’s regular expression library?
A) from re import *
51) Which character encoding standard uses sequences of between 1 and 4 bytes to represent a huge number of different characters?
A) UTF-8

52) Which of the following statements should be used to open a file that might contain special characters (such as accents, Greek letters or musical symbols) for reading?
A) inf = open(“input.txt”, “r”, encoding=”utf-8″)

53) Given the following command line, where are the arguments stored?

python program.py -v input.dat

A) argv list

54) Assume that your program is started with the following command:

python myProgram.py -z 100

What will be displayed by the following statement?

print(sys.argv[0])

A) myProgram.py

55) Assume that your program is started with the following command:

python myProgram.py the quick brown fox

What will be displayed by the following statement?

print(sys.argv[5])

A) The program will raise an exception

56) Which statement must appear in a program before the command line arguments can be accessed?
A) from sys import argv

57) How is a program executed or started from the command line?
A) Typing the name of the program at the prompt in a terminal window

58) If a program is invoked with python program.py -r input.dat output.dat, what are the elements of argv?
A) argv[0]: “program.py”
argv[1]: “-r”
argv[2]: “input.dat”
argv[3]: “output.dat”

59) Which of the following is not a function that resides in Python’s os module?
A) open

60) Consider the following code segment:

import os


filename = input("Enter the name of a file: ")
if ____________________ :
  print("That file exists!")
else:
  print("That file does not exist.")

This code segment is supposed to print an appropriate message indicating whether or not the file specified by the user exists. What code should be placed in the blank so that the code segment performs its intended task?

A) os.path.exists(filename)

61) What modes are used to read and write a binary file?
A) “rb”, “wb”

62) If a Byte consists of 8 Bits, what is the min and max values of one Byte?
A) 0 – 255

63) What is the result of the variable position after the following code snippet is executed?

inFile.seek(0)
inFile.seek(8, SEEK_CUR)
inFile.seek(-3, SEEK_CUR)
position = inFile.tell()

A) 5

64) Which of the following statements opens a binary file for reading?
A) inFile = open(“test.dat”, “rb”)

65) Which of the following statements moves the file marker 4 bytes earlier in a binary file with its file object stored in inFile?
A) inFile.seek(-4, SEEK_CUR)

66) Which of the following statements stores the current position of the file marker for inFile into x?
A) x = inFile.tell()

67) How can you read from a file starting at a designated position in it?

A) Move the file marker prior to a read or write operation.

68) Consider the following code segment:

print("W", end="")
try :
   inFile = open("test.txt", "r")
   line = inFile.readline()
   value = int(line)
   print("X", end="")


except IOError :
   print("Y", end="")


except ValueError :
   print("Z", end="")

What output is generated when this program runs if test.txt is opened successfully and its first line contains the number 5?
A) WX

69) Consider the following code segment:

print("W", end="")
try :
   inFile = open("test.txt", "r")
   line = inFile.readline()
   value = int(line)
   print("X", end="")


except IOError :
   print("Y", end="")


except ValueError :
   print("Z", end="")

What output is generated when this program runs if test.txt is not opened successfully?
A) WY

70) Consider the following code segment:

print("W", end="")
try :
   inFile = open("test.txt", "r")
   line = inFile.readline()
   value = int(line)
   print("X", end="")


except IOError :
   print("Y", end="")


except ValueError :
   print("Z", end="")

What output is generated when this program runs if test.txt is opened successfully and its first line contains the hello world?
A) WZ

71) What exception is raised by the following code segment?

data = ["A", "B", "C", "D"]
print(data[4])

A) IndexError

72) What code should be added to the end of the following code segment to ensure that inFile is always closed, even if an exception is thrown in the code represented by . . . ?

inFile = open("test.txt", "r")
try :
   line = inFile.readline()
   . . .

A) finally :
inFile.close()

73) It is good programming practice to plan for possible exceptions and provide code to handle the exception. Which exception must be handled to prevent a divide by zero logic error?
A) ZeroDivisionError

74) Consider the following code segment:

try :
   inputFile = open("lyrics.txt", "r")
   line = inputFile.readline()
   print(line)
_____________________
   print("Error")

What should be placed in the blank so that the program will print Error instead of crashing if an exception occurs while opening or reading from the file?

A) except IOError :

75) Consider the following code segment:

try :
   inputFile = open("lyrics.txt", "r")
   line = inputFile.readline()
   words = line.split()
   print(words[len(words)])
_____________________
   print("Error.")

The statement print(words[len(words)]) will raise an exception. What should be placed in the blank so that this exception will be caught and the error message will be displayed?
A) except IndexError :

76) Python’s error handling process includes the finally clause. In the following code snippet, when is the finally clause executed?

inputFile = open("lyrics.txt", "r")
try :
   line = inputFile.readline()
   words = line.split()
   print(words)
finally :
   inputfile.close()

A) The finally clause is always executed in this example.

77) Which of the following is NOT a valid exception in Python?

A) TryError

78) When your program contains logic to read one or more files, which of the following statements is NOT true about the error handling logic needed:
A) The file name might be too long

79) Consider the following code segment:

done = False
while not done :
   try :
      filename = input("Enter the file name: ")
      inFile = open(filename, "r")
      ____________________
   except IOError :
      print("Error: File not found.")

It is supposed to keep on prompting the user for file names until the user provides the name of a file that can be opened successfully. What line of code should be placed in the blank to achieve this goal?
A) done = True
80) Consider the following function call for computing a linear regression:

result = scipy.stats.linregress(data1, data2)

 What is stored in result when this function call completes?

A) A tuple containing the slope, intercept and correlation coefficient for the data sets.
81) Which type of chart can be used to represent the relationship between three dimensional data?
A) A bubble chart

82) Consider the following code segment:

line = input()
  try:
    ...
    if line == "":
      ____________________
    ...


  except RuntimeError:
    print("A blank line was encountered.")

This code segment is supposed to print out A blank line was encountered when a blank line is entered by the user. What code should be placed in the blank so that it will accomplish this goal?
A) raise RuntimeError

83) Which function is not part of the Python statistics module?
A) average
 

Leave a Reply

Your email address will not be published. Required fields are marked *