Exit Chapter 05A ยท ๐Ÿ—‚๏ธ File Handling in Python (Text File) โ€” Quiz

Playing as a guest? to earn XP and track your progress.

Question 1 of 52 0 correct so far

๐Ÿ—‚๏ธ File Handling in Python (Text File) Quiz

Q1.

Which of the following is the correct syntax to open a file in Python?

Explanation

The built-in open() function is used to open files: f = open(filename, mode). It returns a file object.

Q2.

What does the open() function return?

Explanation

open() returns a file object (also called a file handle) that is used for all read/write operations on the file.

Q3.

Which file mode opens a file for reading only and raises an error if the file does not exist?

Explanation

Mode 'r' (read) is the default. It opens the file for reading only. If the file does not exist, it raises FileNotFoundError.

Q4.

Which file mode DESTROYS existing file content when the file is opened?

Explanation

Mode 'w' (write) creates a new file or overwrites existing content without any warning. Always use 'a' if you want to preserve existing data.

Q5.

You want to add new records at the end of an existing file without deleting old data. Which mode should you use?

Explanation

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.

Q6.

Which file mode allows BOTH reading and writing, and requires the file to already exist?

Explanation

Mode 'r+' opens the file for both reading and writing. The file must already exist โ€” it raises FileNotFoundError if not found.

Q7.

What is the default file opening mode if no mode is specified in open()?

Explanation

If no mode argument is provided, open() defaults to 'r' (read mode).

Q8.

Which method reads the entire content of a text file as a single string?

Explanation

read() reads and returns the complete file content as one single string, including all newline characters.

Q9.

Which method reads ONE line from a file, including the trailing \n?

Explanation

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.

Q10.

Which method reads ALL lines from a file and returns them as a list of strings?

Explanation

readlines() reads all lines and returns a list where each element is one line (including its \n character).

Q11.

What does readline() return when the end of the file is reached?

Explanation

When readline() reaches the end of file, it returns an empty string "" (not None or -1). This is used to detect EOF in loops.

Q12.

What does f.read(5) do?

Explanation

read(n) reads exactly n characters from the current file pointer position and advances the pointer by n.

Q13.

Which method writes a single string to a file?

Explanation

write(string) writes a single string to the file. It does NOT add a newline automatically โ€” you must include \n if needed.

Q14.

What does write() return?

Explanation

write(s) returns an integer โ€” the number of characters that were written to the file.

Q15.

Which method is used to write a list of strings to a file?

Explanation

writelines(list) accepts a list (or any iterable) of strings and writes them all to the file one after another.

Q16.

What does writelines() return?

Explanation

writelines() returns None. This is different from write() which returns the character count.

Q17.

If f.writelines(["Math", "Physics", "CS"]) is called, what will the file contain?

Explanation

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.

Q18.

What is the purpose of f.close()?

Explanation

close() flushes all buffered data to disk, releases the file handle (system resource), and marks the file as closed. Always close files after use.

Q19.

What is the purpose of the flush() method?

Explanation

flush() forces Python to immediately write all buffered data to the actual disk file โ€” without closing it. The file stays open for further operations.

Q20.

Why does Python use an I/O buffer when writing files?

Explanation

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.

Q21.

Which with statement correctly opens a file for reading?

Explanation

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.

Q22.

What happens to the file when you use the with statement and exit the with block?

Explanation

The with statement (context manager) automatically closes the file when the indented block ends. No explicit f.close() is needed.

Q23.

Which strip method removes whitespace from BOTH the left and right sides of a string?

Explanation

strip() removes whitespace (spaces, tabs, \n) from both ends of the string. lstrip() is left-only, rstrip() is right-only.

Q24.

When reading a file line by line, why should you use .strip() before comparing?

Explanation

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.

Q25.

What is the output?

line = "  Hello  \n"
print(repr(line.rstrip()))
Explanation

rstrip() removes whitespace from the right side only. The trailing \n and spaces are removed but leading spaces remain: ' Hello'.

Q26.

What does the tell() method return?

Explanation

tell() returns an integer representing the current byte position of the file pointer from the beginning of the file.

Q27.

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()
Explanation

tell() starts at 0 (beginning). After read(5) reads 5 characters ('Hello'), the pointer advances to position 5.

Q28.

What does f.seek(0) do?

Explanation

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.

Q29.

What is the syntax of the seek() method?

Explanation

seek(offset, from_where) โ€” offset is the number of bytes to move, from_where is the reference: 0=beginning (default), 1=current, 2=end.

Q30.

In text mode, which seek() operation is NOT reliably supported?

Explanation

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.

Q31.

Text files store data as:

Explanation

Text files store data as human-readable characters encoded in ASCII or Unicode. They can be opened and read in any text editor.

Q32.

Binary files store data as:

Explanation

Binary files store data as raw bytes, exactly as it exists in RAM. They are not human-readable and require special programs to open.

Q33.

Which of the following is a text file extension?

Explanation

.csv (Comma Separated Values) is a text file. .jpg, .mp3, and .pkl are binary files.

Q34.

Which of the following is a binary file extension?

Explanation

.pkl (pickle file) is a binary file used by Python's pickle module. .txt, .py, and .html are all text files.

Q35.

What exception is raised when you try to open a non-existent file in 'r' mode?

Explanation

FileNotFoundError is raised when open() cannot find the file. This is a subclass of OSError.

Q36.

What is the difference between 'w' and 'a' mode?

Explanation

'w' (write) destroys all existing content when the file is opened. 'a' (append) preserves existing content and adds new data at the end.

Q37.

What is sys.stdin in Python?

Explanation

sys.stdin is the standard input stream โ€” it reads from the keyboard by default. The input() function is a convenient wrapper around sys.stdin.

Q38.

What is sys.stdout in Python?

Explanation

sys.stdout is the standard output stream โ€” it writes to the console/screen by default. The print() function internally uses sys.stdout.

Q39.

What is sys.stderr used for?

Explanation

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.

Q40.

Which module must be imported to access stdin, stdout, and stderr?

Explanation

The sys module provides access to sys.stdin, sys.stdout, and sys.stderr โ€” the three standard I/O streams.

Q41.

What is the output?

f = open("test.txt", "w")
f.write("Python")
f.write("Files")
f.close()
# test.txt now contains:
Explanation

write() does NOT add any separator or newline. Both strings are written consecutively: PythonFiles. To separate, you must write "Python\nFiles".

Q42.

A file data.txt already has some content. What happens when you open it with open("data.txt", "w")?

Explanation

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!

Q43.

Which property of a file object tells you if a file is closed?

Explanation

f.closed is a boolean attribute. It returns True if the file is closed, False if it's still open.

Q44.

What is the output?

with open("test.txt", "w") as f:
    f.write("Hello")
print(f.closed)
Explanation

After the with block exits, the file is automatically closed. So f.closed returns True.

Q45.

What does readlines() include in each list element?

Explanation

readlines() includes the trailing \n character in each string element. Use .strip() on each element to remove it.

Q46.

Which is the most memory-efficient way to read a very large file line by line?

Explanation

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.

Q47.

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()
Explanation

readlines() returns a list where each line is an element. The file has 2 lines, so len(lines) = 2.

Q48.

Where is the file pointer placed when a file is opened in 'a' (append) mode?

Explanation

In append mode 'a', the file pointer is placed at the end of the file. All writes add new content after the existing content.

Q49.

Where is the file pointer placed when a file is opened in 'r' (read) mode?

Explanation

In read mode 'r', the file pointer starts at the beginning (position 0) of the file.

Q50.

What is the output?

f = open("data.txt", "w")
n = f.write("Hello")
print(n)
f.close()
Explanation

write() returns the number of characters written. "Hello" has 5 characters, so it returns 5.

Q51.

Why should you always use .strip() when reading lines from a file?

Explanation

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.

Q52.

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()
Explanation

writelines() writes 3 strings each ending with \n, creating 3 separate lines. readlines() returns a list of 3 elements, so len() = 3.