Teach Computer
Science
File handling
teachcomputerscience.co
m
Quiz
1. What does the following code do?
f=open("test.txt")
A. Opens the file in write mode
B. Opens the file in read mode
C. Opens the file for both reading and writing
D. Syntax error
2. What happens when you try to open a file that does not
exist using the code?
with open("test.txt",'w') as f:
A. A new file is created
B. Error message pops up
C. Nothing happens
D. None of the above
3. What does opening a file in mode ‘a’ mean?
with open("test.txt“, ‘a’) as f:
A. Opens text.txt for reading
B. Opens text.txt for writing
C. Opens text.txt for appending text at the end of the file
D. None of the above
teachcomputerscience.co
m
Use the file test1.txt to answer questions 4-6
This is now opened using this code: f=open("test1.txt",'r')
4. What is the output of f.read(15)?
A. 'This is a text file‘
B. 'This is a text‘
C. 'This is a text ‘
D. None of the above
5. After executing f.read(15), the code f.read(10) returns what
output?
A. 'This is a ‘
B. 'file.\nIt h‘
C. ‘ file.\nIt'
D. None of the above
6. After executing f.read(15) and f.read(10), now f.read() is
executed. What is the output?
A. 'as three lines.\nI am processing it using Python.‘
B. ‘has three lines.\nI am processing it using Python.'
C. 'This is a text file.\nIt has three lines.\nI am processing it
using Python.'
teachcomputerscience.co
m
7. Which of the following prints contents of a file line by line?
A. with open("test.txt") as f:
for line in f:
print(line, end='')
B. with open("test.txt“,’w’) as f:
for line in f:
print(line, end='')
C. with open("test.txt“, ‘r’) as f
for line in f
print(line, end='')
D. with open("test.txt") as f:
f.read()
8. Which of the following is used to separate a line into words?
A. words()
B. linestowords()
C. separate()
D. split()
teachcomputerscience.co
m
Answers
Question
Answer
Number
1 B
2 A
3 C
4 C
5 B
6 A
7 A
8 D
teachcomputerscience.co
m