Playing as a guest? to earn XP and track your progress.
๐๏ธ File Handling in Python (Text File) Quiz
๐๏ธ File Handling in Python (Text File)
Which of the following is the correct syntax to open a file in Python?
file.open("data.txt", "r")
f = open("data.txt", "r")
f = file("data.txt", "r")
open file "data.txt" as f
The built-in open() function is used to open files: f = open(filename, mode). It returns a file object.
What does the open() function return?
The contents of the file
A string with the file name
A file object (file handle)
A boolean True/False
open() returns a file object (also called a file handle) that is used for all read/write operations on the file.
Which file mode opens a file for reading only and raises an error if the file does not exist?
'w'
'a'
'r'
'r+'
Mode 'r' (read) is the default. It opens the file for reading only. If the file does not exist, it raises FileNotFoundError.
Which file mode DESTROYS existing file content when the file is opened?
'r'
'a'
'w'
'r+'
Mode 'w' (write) creates a new file or overwrites existing content without any warning. Always use 'a' if you want to preserve existing data.
You want to add new records at the end of an existing file without deleting old data. Which mode should you use?
'w'
'r'
'a'
'r+'
Mode 'a' (append) places the file pointer at the end of the file and adds new content after existing content โ it never erases old data.
Which file mode allows BOTH reading and writing, and requires the file to already exist?
'w+'
'a+'
'r+'
'rw'
Mode 'r+' opens the file for both reading and writing. The file must already exist โ it raises FileNotFoundError if not found.
What is the default file opening mode if no mode is specified in open()?
'w'
'a'
'r'
'r+'
If no mode argument is provided, open() defaults to 'r' (read mode).
Which method reads the entire content of a text file as a single string?
readline()
readlines()
read()
readall()
read() reads and returns the complete file content as one single string, including all newline characters.
Which method reads ONE line from a file, including the trailing \n?
read()
readlines()
readline()
readone()
readline() reads and returns one line at a time, including its \n at the end. Each call advances the file pointer to the next line.
Which method reads ALL lines from a file and returns them as a list of strings?
read()
readline()
readlines()
readall()
readlines() reads all lines and returns a list where each element is one line (including its \n character).
What does readline() return when the end of the file is reached?
None
False
An empty string ""
-1
When readline() reaches the end of file, it returns an empty string "" (not None or -1). This is used to detect EOF in loops.
What does f.read(5) do?
Reads 5 lines from file
Reads the file 5 times
Reads exactly 5 characters from the current position
Reads the 5th line of the file
read(n) reads exactly n characters from the current file pointer position and advances the pointer by n.
Which method writes a single string to a file?
writelines()
writeline()
write()
print()
write(string) writes a single string to the file. It does NOT add a newline automatically โ you must include \n if needed.
What does write() return?
None
True
The string written
The number of characters written
write(s) returns an integer โ the number of characters that were written to the file.
Which method is used to write a list of strings to a file?
write()
writeline()
writelines()
writeall()
writelines(list) accepts a list (or any iterable) of strings and writes them all to the file one after another.
What does writelines() return?
Number of lines written
Number of characters written
None
True
writelines() returns None. This is different from write() which returns the character count.
If f.writelines(["Math", "Physics", "CS"]) is called, what will the file contain?
Math\nPhysics\nCS
Math Physics CS
MathPhysicsCS
Error
writelines() does NOT add newlines or separators between items. All strings are written consecutively: MathPhysicsCS. You must include \n in each string if you want separate lines.
What is the purpose of f.close()?
Deletes the file
Reads remaining data
Flushes buffer and releases the file handle
Resets the file pointer to start
close() flushes all buffered data to disk, releases the file handle (system resource), and marks the file as closed. Always close files after use.
What is the purpose of the flush() method?
Closes the file immediately
Deletes all file content
Forces buffered data to be written to disk without closing the file
Resets the file pointer
flush() forces Python to immediately write all buffered data to the actual disk file โ without closing it. The file stays open for further operations.
Why does Python use an I/O buffer when writing files?
To encrypt file data
To reduce the number of disk operations and improve performance
To check for syntax errors
To compress the file
Python collects write operations in an in-memory buffer and writes them to disk in one batch โ this is much faster than writing to disk for every single write() call.
Which with statement correctly opens a file for reading?
with open('data.txt') as f:
with file.open('data.txt') as f:
using open('data.txt') as f:
open('data.txt') with f:
with open('data.txt') as f: is the correct syntax. The with statement ensures the file is automatically closed when the block finishes, even if an exception occurs.
What happens to the file when you use the with statement and exit the with block?
The file is deleted
The file is automatically closed
The file pointer moves to position 0
Nothing โ file stays open
The with statement (context manager) automatically closes the file when the indented block ends. No explicit f.close() is needed.
Which strip method removes whitespace from BOTH the left and right sides of a string?
lstrip()
rstrip()
strip()
trim()
strip() removes whitespace (spaces, tabs, \n) from both ends of the string. lstrip() is left-only, rstrip() is right-only.
When reading a file line by line, why should you use .strip() before comparing?
To convert string to integer
To remove the hidden trailing \n character
To make the string uppercase
To remove all spaces inside the string
Every line read from a file includes the trailing \n. So line == "Python" will always be False because line is actually "Python\n". .strip() removes the \n, making comparison work correctly.
What is the output?
line = " Hello \n"
print(repr(line.rstrip()))'Hello'
' Hello'
'Hello '
' Hello '
rstrip() removes whitespace from the right side only. The trailing \n and spaces are removed but leading spaces remain: ' Hello'.
What does the tell() method return?
The name of the file
The number of lines in the file
The current byte position of the file pointer
The file size in KB
tell() returns an integer representing the current byte position of the file pointer from the beginning of the file.
What is the output?
f = open("hello.txt", "r")
# hello.txt contains: "Hello World"
print(f.tell())
f.read(5)
print(f.tell())
f.close()0 then 5
0 then 0
5 then 5
0 then Hello
tell() starts at 0 (beginning). After read(5) reads 5 characters ('Hello'), the pointer advances to position 5.
What does f.seek(0) do?
Closes the file
Reads 0 characters
Moves the file pointer back to the beginning of the file
Writes 0 bytes to the file
seek(0) moves the file pointer to byte position 0 โ the very beginning of the file. This allows re-reading the file from the start.
What is the syntax of the seek() method?
seek(position)
seek(offset, from_where)
seek(file, offset)
seek(from_where, offset)
seek(offset, from_where) โ offset is the number of bytes to move, from_where is the reference: 0=beginning (default), 1=current, 2=end.
In text mode, which seek() operation is NOT reliably supported?
seek(0)
seek(5, 0)
seek(2, 1)
seek(0, 0)
In text mode, seek(n, 1) (from current position) and seek(n, 2) (from end) are not reliably supported. Only seek(0) and seek(n, 0) (from beginning) work reliably.
Text files store data as:
Raw bytes
Human-readable characters (ASCII/Unicode)
Compressed binary
Encrypted data
Text files store data as human-readable characters encoded in ASCII or Unicode. They can be opened and read in any text editor.
Binary files store data as:
Human-readable characters
Raw bytes โ exactly as stored in RAM
JSON format
Comma-separated values
Binary files store data as raw bytes, exactly as it exists in RAM. They are not human-readable and require special programs to open.
Which of the following is a text file extension?
.jpg
.pkl
.mp3
.csv
.csv (Comma Separated Values) is a text file. .jpg, .mp3, and .pkl are binary files.
Which of the following is a binary file extension?
.txt
.py
.pkl
.html
.pkl (pickle file) is a binary file used by Python's pickle module. .txt, .py, and .html are all text files.
What exception is raised when you try to open a non-existent file in 'r' mode?
ValueError
IOError
FileNotFoundError
OSError
FileNotFoundError is raised when open() cannot find the file. This is a subclass of OSError.
What is the difference between 'w' and 'a' mode?
'w' reads, 'a' writes
'w' erases existing content; 'a' adds to end without erasing
'a' erases existing content; 'w' appends
Both do the same thing
'w' (write) destroys all existing content when the file is opened. 'a' (append) preserves existing content and adds new data at the end.
What is sys.stdin in Python?
Standard output stream
Standard input stream (keyboard by default)
Standard error stream
Standard file stream
sys.stdin is the standard input stream โ it reads from the keyboard by default. The input() function is a convenient wrapper around sys.stdin.
What is sys.stdout in Python?
Standard input stream
Standard error stream
Standard output stream (screen by default)
Standard file stream
sys.stdout is the standard output stream โ it writes to the console/screen by default. The print() function internally uses sys.stdout.
What is sys.stderr used for?
Reading keyboard input
Writing normal program output
Writing error and warning messages (separate from stdout)
Reading from files
sys.stderr is the standard error stream โ it displays error and warning messages. It is separate from stdout so errors appear even if stdout is redirected.
Which module must be imported to access stdin, stdout, and stderr?
os
io
sys
file
The sys module provides access to sys.stdin, sys.stdout, and sys.stderr โ the three standard I/O streams.
What is the output?
f = open("test.txt", "w")
f.write("Python")
f.write("Files")
f.close()
# test.txt now contains:Python\nFiles
Python Files
PythonFiles
Error
write() does NOT add any separator or newline. Both strings are written consecutively: PythonFiles. To separate, you must write "Python\nFiles".
A file data.txt already has some content. What happens when you open it with open("data.txt", "w")?
New content is appended to existing content
Existing content is preserved
Existing content is ERASED and file becomes empty
FileNotFoundError is raised
Opening an existing file in 'w' mode immediately erases all its content and creates a fresh empty file. This happens even before you write anything!
Which property of a file object tells you if a file is closed?
f.status
f.is_closed
f.closed
f.state
f.closed is a boolean attribute. It returns True if the file is closed, False if it's still open.
What is the output?
with open("test.txt", "w") as f:
f.write("Hello")
print(f.closed)False
True
Error
None
After the with block exits, the file is automatically closed. So f.closed returns True.
What does readlines() include in each list element?
Only the text, no newline
The line number followed by text
The text including the trailing \n character
Only the first word of each line
readlines() includes the trailing \n character in each string element. Use .strip() on each element to remove it.
Which is the most memory-efficient way to read a very large file line by line?
f.read()
f.readlines()
for line in f: (direct iteration)
f.readline() in a while loop
Direct iteration for line in f: is the most memory-efficient โ Python reads one line at a time without loading the entire file into RAM. readlines() loads everything at once.
What is the output?
f = open("poem.txt", "r")
# poem.txt: "Roses are red,\nViolets are blue,"
lines = f.readlines()
print(len(lines))
f.close()1
2
3
Error
readlines() returns a list where each line is an element. The file has 2 lines, so len(lines) = 2.
Where is the file pointer placed when a file is opened in 'a' (append) mode?
At the beginning of the file
At the middle of the file
At the end of the file
At position -1
In append mode 'a', the file pointer is placed at the end of the file. All writes add new content after the existing content.
Where is the file pointer placed when a file is opened in 'r' (read) mode?
At the end of the file
At position -1
At the beginning of the file
At the middle
In read mode 'r', the file pointer starts at the beginning (position 0) of the file.
What is the output?
f = open("data.txt", "w")
n = f.write("Hello")
print(n)
f.close()Hello
None
5
True
write() returns the number of characters written. "Hello" has 5 characters, so it returns 5.
Why should you always use .strip() when reading lines from a file?
To convert string to list
To remove hidden \n characters that cause double-spacing and comparison bugs
To decrypt file content
To count characters in the line
Each line read from a file has a trailing \n. This causes double-blank lines when printed and makes string comparisons fail. .strip() cleans this up.
What is the output?
f = open("test.txt", "w")
f.writelines(["Math\n", "Physics\n", "CS\n"])
f.close()
f = open("test.txt", "r")
print(len(f.readlines()))
f.close()1
2
3
6
writelines() writes 3 strings each ending with \n, creating 3 separate lines. readlines() returns a list of 3 elements, so len() = 3.