Python File Handling MCQ Questions and Answers
Q. What is the mode in which a file is opened for both reading and writing?
A. 'r'B. 'w'
C. 'r+'
D. 'a'
Q. What is the correct way to open a file named "data.txt" in append mode?
A. file = open("data.txt", "a")B. file = open("data.txt", "w")
C. file = open("data.txt", "r+")
D. file = open("data.txt", "a+")
Q. What is the correct way to read the entire content of a file at once?
A. file.read()B. file.readlines()
C. file.readall()
D. file.readlinesall()
Q. What is the correct way to write a string to a file?
A. file.write("Hello, World!")B. file.put("Hello, World!")
C. file.append("Hello, World!")
D. file.add("Hello, World!")
Q. What is the correct way to close a file?
A. file.close()B. file.open(mode="closed")
C. file.end()
D. file = None
Q. What is the purpose of the "with" statement when working with files?
A. To open a file in a specific modeB. To ensure the file is properly closed after usage
C. To create a new file
D. To delete a file
Q. What is the correct way to read lines from a file and store them in a list?
A. lines = file.readlines()B. lines = file.readlist()
C. lines = file.readlineslist()
D. lines = file.readall()
Q. How can you check if a file exists before attempting to open it?
A. file.exists()B. os.path.exists(file)
C. file.is_file()
D. file.isfile()
Q. What is the purpose of the "tell()" method in file handling?
A. To get the current position in the fileB. To set the position in the file
C. To get the size of the file
D. To check if the file is empty
Q. What is the purpose of the "seek()" method in file handling?
A. To set the position in the fileB. To get the current position in the file
C. To get the size of the file
D. To check if the file is empty
Q. What is the correct way to rename a file?
A. os.rename("old_file.txt", "new_file.txt")B. file.rename("old_file.txt", "new_file.txt")
C. file.move("old_file.txt", "new_file.txt")
D. os.move("old_file.txt", "new_file.txt")
Q. What is the correct way to delete a file?
A. os.remove("file.txt")B. file.remove("file.txt")
C. file.delete("file.txt")
D. os.delete("file.txt")