File handling is an integral part of programming, allowing us to interact with external files. Python provides a variety of methods to perform file operations, from reading and writing to deleting files. Let’s test your knowledge on Python’s file handling with these multiple choice questions!
Note that each question is followed by the correct answer and an explanation to help reinforce your knowledge.
1. Which method in Python is used to read the entire contents of the file?
Answer:
Explanation:
The read() method is used to read the entire content of the file.
2. Which mode is used to open a file for writing only?
Answer:
Explanation:
The mode w stands for “write”. It opens the file for writing only.
3. What will be the output of the following code if the file contains “Hello World!”?
f = open("test.txt", "r")
print(f.readline())
Answer:
Explanation:
readline() method reads the next line from the file.
4. How do you create a new file in Python?
Answer:
Explanation:
Using open with mode ‘x’ creates a new file. If the file already exists, it raises a FileExistsError.
5. Which function closes an opened file?
Answer:
Explanation:
The close() method is used to close an opened file. It’s a good practice to close files to free up system resources.
6. Which method returns a list of lines in the file?
Answer:
Explanation:
The readlines() method reads all lines in a file and returns them as a list.
7. If a file is opened in write mode (w), what happens?
Answer:
Explanation:
Opening a file in w mode truncates the file content. If the file doesn’t exist, it will be created.
8. Which mode is used to open a file for appending?
Answer:
Explanation:
The mode a stands for “append”. It opens the file for appending.
9. What is the purpose of the os module in relation to file handling?
Answer:
Explanation:
The os module in Python provides a way of using system-dependent functionality, such as reading or writing to the file system.
10. How can you read a file line by line using a loop?
Answer:
Explanation:
In Python, a file object is iterable. We can iterate over it line by line using a for loop.
File handling is a fundamental skill for any Python developer. Keep practicing and exploring the Python documentation to master this crucial area!