Python File Input and Output 2 — Questions and Answers
Question 1: What does the 'a+' mode do when opening a file in Python?
- Opens for reading only, pointer at start
- Opens for reading and writing, pointer at end, creates file if missing (Correct answer)
- Opens for writing only, truncates file
- Opens for reading and writing, truncates file
Correct answer: Opens for reading and writing, pointer at end, creates file if missing
The 'a+' mode opens a file for both reading and appending; the pointer is at the end and the file is created if it does not exist.
Question 2: Which method reads all lines of a file into a list?
- file.read()
- file.readline()
- file.readlines() (Correct answer)
- file.readall()
Correct answer: file.readlines()
file.readlines() returns a list where each element is a line from the file including the newline character.
Question 3: What happens if you call open() with mode 'x' on a file that already exists?
- It truncates and overwrites the file
- It appends to the existing file
- It raises a FileExistsError (Correct answer)
- It returns None
Correct answer: It raises a FileExistsError
Mode 'x' is exclusive creation; it raises FileExistsError if the file already exists.
Question 4: What does the os.path.getsize() function return?
- Number of lines in the file
- File size in bytes (Correct answer)
- File size in kilobytes
- Number of characters in the file
Correct answer: File size in bytes
os.path.getsize(path) returns the size of the file at the given path in bytes.
Question 5: Which built-in function is used to rename a file in Python?
- os.rename() (Correct answer)
- file.rename()
- shutil.rename()
- os.move()
Correct answer: os.rename()
os.rename(src, dst) renames the file or directory from src to dst.
Question 6: What is the default encoding used by open() on most modern Python installations?
- ascii
- utf-16
- The locale/platform default (often utf-8) (Correct answer)
- latin-1
Correct answer: The locale/platform default (often utf-8)
If encoding is not specified, open() uses the locale-preferred encoding, which is utf-8 on most modern systems.
Question 7: Which statement about binary mode ('rb') is TRUE?
- Newlines are automatically converted
- Data is returned as str objects
- Data is returned as bytes objects (Correct answer)
- The file must already contain binary data
Correct answer: Data is returned as bytes objects
In binary mode, read operations return bytes objects instead of str, with no newline translation.
What does the 'a+' mode do when opening a file in Python?