PCAP File I/O and String Operations 1 — Questions and Answers
Question 1: Which built-in function is used to open a file in Python?
- file()
- open() (Correct answer)
- read()
- load()
Correct answer: open()
The `open()` function opens a file and returns a file object for reading or writing.
Question 2: What mode string opens a file for writing, creating it if it does not exist and truncating if it does?
- 'r'
- 'a'
- 'w' (Correct answer)
- 'x'
Correct answer: 'w'
Mode `'w'` opens a file for writing, creating it if absent and clearing it if it exists.
Question 3: What does the `with` statement do when used with `open()`?
- Opens the file in binary mode
- Automatically closes the file when the block exits (Correct answer)
- Locks the file from other processes
- Buffers writes
Correct answer: Automatically closes the file when the block exits
The `with` statement is a context manager that ensures the file is closed when the block ends, even on exceptions.
Question 4: Which method reads the entire file content as a single string?
- readline()
- readlines()
- read() (Correct answer)
- fetch()
Correct answer: read()
`file.read()` reads the entire file and returns it as a single string.
Question 5: What does `file.readlines()` return?
- A single string
- A list of strings, one per line (Correct answer)
- A generator of lines
- A bytes object
Correct answer: A list of strings, one per line
`readlines()` reads all lines and returns them as a list of strings including newline characters.
Question 6: Which file mode opens a file for appending without truncating existing content?
- 'w'
- 'r+'
- 'a' (Correct answer)
- 'x'
Correct answer: 'a'
Mode `'a'` opens a file for appending; writes go to the end without erasing existing data.
Which built-in function is used to open a file in Python?