File Input and Output Flashcards
6 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 6 File Input and Output flashcards as text
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?
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.
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?
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.
What is the primary difference in the return value between the `read()` and `readlines()` file methods in Python?
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.
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) ```
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.
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)) ```
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'.
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?
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'`.