1
How do you open a file named data.txt in read mode in Python?
A)
file = open('data.txt', 'r')
B)
file = open('data.txt', 'read')
C)
file = open('data.txt', 'read mode')
D)
file = open('data.txt')
Answer & Solution
Answer: Option
A
2
What is the purpose of the with statement in file handling?
A)
It ensures that the file is properly closed after usage
B)
It creates a new file
C)
It reads the file contents
D)
It deletes the file
Answer & Solution
Answer: Option
A
3
How can you write data to a file in Python?
A)
By using the write() method on a file object
B)
By using the save() function
C)
By using the put() function
D)
By using the append() method
Answer & Solution
Answer: Option
A
4
What does the read() method of a file object do?
A)
It reads the entire contents of the file
B)
It writes data to the file
C)
It closes the file
D)
It deletes the file
Answer & Solution
Answer: Option
A
5
How can you read a single line from a file in Python?
A)
By using the readline() method on a file object
B)
By using the line() function
C)
By using the get_line() method
D)
By using the read() method
Answer & Solution
Answer: Option
A
6
What is the purpose of the seek() method in file handling?
A)
It changes the file position to a specified offset
B)
It searches for a string in the file
C)
It appends data to the end of the file
D)
It reads a specific line
Answer & Solution
Answer: Option
A
7
How can you read the entire contents of a file line by line in Python?
A)
By using a for loop with the file object
B)
By using the readlines() method on a file object
C)
By using the readline() method on a file object
D)
By using the line() function
Answer & Solution
Answer: Option
B
8
What is the output of the following code:with open('data.txt', 'a') as file: file.write('Appended line.') with open('data.txt', 'r') as file: content = file.read() print(content)
A)
Contents of data.txt with the appended line
B)
An error will occur
C)
Appended line.
D)
file object
Answer & Solution
Answer: Option
D
9
How can you create a new file in Python if it doesn't exist?
A)
By using the 'x' mode when opening the file
B)
By using the 'create' keyword
C)
By using the new() function
D)
By using the 'c' mode when opening the file
Answer & Solution
Answer: Option
A
10
To open a file c:\scores.txt for reading, we use . . . . . . . .
A)
infile = open(“c:\scores.txt”, “r”)
B)
infile = open(“c:\\scores.txt”, “r”)
C)
infile = open(file = “c:\scores.txt”, “r”)
D)
infile = open(file = “c:\\scores.txt”, “r”)
Answer & Solution
Answer: Option
B