Python File Input and Output Questions and Answers — Questions and Answers
Question 1: Which of the following is the most idiomatic and safest way to open a file for writing in Python, ensuring that it is always closed properly?
- file = open('data.txt', 'w'); file.write('content'); file.close()
- try: file = open('data.txt', 'w') file.write('content') finally: file.close()
- with open('data.txt', 'w') as file: file.write('content') (Correct answer)
- def write_file(): file = open('data.txt', 'w') file.write('content') return file.close()
Correct answer: with open('data.txt', 'w') as file: file.write('content')
The `with` statement is the recommended way to handle file objects. It automatically takes care of closing the file when the block is exited, even if an exception occurs within the block. This prevents resource leaks and is more concise than a `try...finally` block.
Question 2: A developer needs to write a logging function that adds new entries to the end of a log file. If the log file does not exist, it should be created. The function also needs to be able to read from the file to check previous logs. Which file mode is the most appropriate for this scenario?
- 'w+'
- 'r+'
- 'a'
- 'a+' (Correct answer)
Correct answer: 'a+'
The 'a+' mode is ideal for this use case. The 'a' stands for append, which means the file pointer is placed at the end of the file for writing, and if the file doesn't exist, it will be created. The '+' signifies that the file is opened for updating (both reading and writing). 'w+' would truncate the file, 'r+' would raise an error if the file doesn't exist, and 'a' would not allow reading.
Question 3: What is the primary difference in the return value between the `read()` and `readlines()` file methods in Python?
- `read()` returns a list of lines, while `readlines()` returns a single string containing the entire file content.
- `read()` returns a single string containing the entire file content, while `readlines()` returns a list of strings, where each string is a line from the file. (Correct answer)
- `read()` returns a generator object for iterating over lines, while `readlines()` loads all lines into memory at once.
- Both methods return a list of strings, but `readlines()` includes newline characters while `read()` does not.
Correct answer: `read()` returns a single string containing the entire file content, while `readlines()` returns a list of strings, where each string is a line from the file.
The `file.read()` method, when called without an argument, reads the entire content of a file and returns it as a single string. In contrast, the `file.readlines()` method reads all lines from the file and returns them as a list of strings, with each string in the list representing one line and including the trailing newline character.
Question 4: After executing the following code, what will be the content of 'report.txt'? ```python lines = ['- Item 1', '- Item 2', '- Item 3'] with open('report.txt', 'w') as f: f.writelines(lines) ```
- - Item 1\n- Item 2\n- Item 3\n
- - Item 1 - Item 2 - Item 3
- ['- Item 1', '- Item 2', '- Item 3']
- - Item 1- Item 2- Item 3 (Correct answer)
Correct answer: - Item 1- Item 2- Item 3
The `writelines()` method takes an iterable of strings and writes each string to the file consecutively. However, it does not add any line separators like newlines (`\n`) between the strings. Since the strings in the `lines` list do not contain newline characters, they will be concatenated directly in the file.
Question 5: Given a file named 'data.txt' containing the text 'ABCDEFG', what will the following Python code print? ```python with open('data.txt', 'r') as f: f.read(3) f.seek(1) print(f.read(2)) ```
- AB
- DE
- BC (Correct answer)
- CD
Correct answer: BC
First, `f.read(3)` reads 'ABC' and moves the file pointer (cursor) to position 3 (after 'C'). Then, `f.seek(1)` moves the pointer to position 1 (after 'A'). Finally, `f.read(2)` reads the next two characters from the current position (1), which are 'B' and 'C'. The output is therefore 'BC'.
Question 6: A developer needs to save a Python dictionary to a file so it can be perfectly reconstructed into a dictionary object later. Which module and file mode should be used for this task?
- The `json` module with the `'w'` mode.
- The `os` module with the `'wb'` mode.
- The `pickle` module with the `'wb'` mode. (Correct answer)
- The `sys` module with the `'w'` mode.
Correct answer: The `pickle` module with the `'wb'` mode.
The `pickle` module is Python's standard library for serializing and de-serializing Python object structures (a process also called 'pickling'). To save a Python object like a dictionary, you should use `pickle.dump()`. This process requires the file to be opened in binary write mode, which is specified by `'wb'`.
Which of the following is the most idiomatic and safest way to open a file for writing in Python, ensuring that it is always closed properly?