This set of Python written test Questions & Answers focuses on “Files”.
1. Which of the following is not a valid mode to open a file?
Explanation: Use r+, w+ or a+ to perform both read and write operations using a single file object.
2. What is the difference between r+ and w+ modes?
a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
c) in w+ the pointer is initially placed at the beginning of the file and the pointer is at the end for r+
d) depends on the operating system
3. How do you get the name of a file from a file object (fp)?
Explanation: name is an attribute of the file object.
4. Which of the following is not a valid attribute of a file object (fp)?
Explanation: fp.size has not been implemented.
5. How do you close a file object (fp)?
Explanation: close() is a method of the file object.
6. How do you get the current position within the file?
Explanation: It gives the current position as an offset from the start of file.
7. How do you rename a file?
a) fp.name = ‘new_name.txt’
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)
Explanation: os.rename() is used to rename files.
8. How do you delete a file?
Explanation: os.remove() is used to delete files.
9. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned
Explanation: 0 indicates that the offset is with respect to the start.
10. What happens if no arguments are passed to the seek function?
a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
Explanation: seek() takes at least one argument.
Sanfoundry Global Education & Learning Series – Python.
To practice all written questions on Python, here is complete set of 1000+ Multiple Choice Questions and Answers.