Python File Handling Basics Quiz

Python
0 Passed
0% acceptance

A 35-question quiz covering file opening, reading, writing, modes, and the importance of context managers.

35 Questions
~70 minutes
1

Question 1

What is the primary purpose of the `open()` function in Python?

A
To return a file object that allows interaction with a file on the disk.
B
To display the contents of a file on the screen immediately.
C
To create a new folder in the file system.
D
To download a file from the internet.
2

Question 2

Analyze the code below. What happens if 'data.txt' does not exist?

python
f = open('data.txt', 'r')
A
FileNotFoundError is raised.
B
A new empty file is created.
C
It returns None.
D
It opens a temporary file.
3

Question 3

Which file mode should you use to add new content to the end of an existing file without deleting its current contents?

A
'a'
B
'w'
C
'r+'
D
'x'
4

Question 4

Analyze the code below. What is the best practice missing from this snippet?

python
f = open('log.txt', 'w')
f.write('Error occurred')
A
The file is not explicitly closed using f.close().
B
The write mode should be 'wb'.
C
The string must end with a newline.
D
It should use print() instead of write().
5

Question 5

What is the main advantage of using the `with open(...)` statement?

A
It automatically closes the file, even if an error occurs within the block.
B
It reads the file faster.
C
It allows opening multiple files with the same name.
D
It automatically converts the file content to JSON.
6

Question 6

Which method reads the *entire* remaining contents of a file as a single string?

A
read()
B
readline()
C
readlines()
D
readall()
7

Question 7

Analyze the code below. What will be the content of 'test.txt' after execution?

python
with open('test.txt', 'w') as f:
    f.write('Hello')
with open('test.txt', 'w') as f:
    f.write('World')
A
World
B
Hello World
C
HelloWorld
D
Hello World
8

Question 8

What does the `readline()` method return when it reaches the end of the file?

A
An empty string ''
B
None
C
EOFError
D
-1
9

Question 9

Which file mode allows you to both read and write to a file?

A
'r+'
B
'rw'
C
'w+'
D
Both A and C
10

Question 10

Analyze the code below. What is the data type of `lines`?

python
with open('data.txt', 'r') as f:
    lines = f.readlines()
A
List of strings
B
String
C
Dictionary
D
Tuple
11

Question 11

What happens if you try to write to a file opened in `'r'` mode?

A
UnsupportedOperation error (not writable)
B
It silently fails.
C
It changes the mode to write automatically.
D
It writes to a temporary buffer.
12

Question 12

How do you ensure that data written to a file is physically saved to the disk immediately without closing the file?

A
f.flush()
B
f.save()
C
f.commit()
D
f.persist()
13

Question 13

Analyze the code below. Why might the output contain double newlines?

python
with open('file.txt', 'r') as f:
    for line in f:
        print(line)
A
Because `line` keeps the file's newline character, and `print()` adds another one.
B
Because the file is corrupted.
C
Because the loop iterates twice per line.
D
Because read mode adds extra spacing.
14

Question 14

Which mode creates a new file for writing but fails if the file already exists?

A
'x'
B
'n'
C
'w-'
D
'c'
15

Question 15

What is the default mode if you omit the mode argument in `open('file.txt')`?

A
'r' (text read)
B
'w' (text write)
C
'rb' (binary read)
D
'a' (append)
16

Question 16

Analyze the code below. What does `f.seek(0)` do?

python
with open('data.txt', 'r') as f:
    content = f.read()
    f.seek(0)
    content_again = f.read()
A
It moves the file cursor back to the beginning of the file.
B
It deletes the file content.
C
It searches for the number 0 in the file.
D
It closes the file.
17

Question 17

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

A
writelines()
B
writelist()
C
write_all()
D
dump()
18

Question 18

What is the difference between opening a file in `'t'` mode vs `'b'` mode?

A
't' handles text (strings), while 'b' handles binary data (bytes).
B
't' is for temporary files, 'b' is for backup.
C
't' is faster than 'b'.
D
'b' is only for images.
19

Question 19

Analyze the code below. What happens if you iterate directly over the file object `f`?

python
with open('story.txt', 'r') as f:
    for line in f:
        pass
A
It reads the file line by line efficiently.
B
It reads the file character by character.
C
It loads the entire file into memory at once.
D
It throws a TypeError.
20

Question 20

Why is it important to specify the `encoding` parameter (e.g., `encoding='utf-8'`) when opening text files?

A
To ensure the file is read/written correctly across different operating systems.
B
To make the file read-only.
C
To compress the file.
D
It is required by syntax.
21

Question 21

What does the `tell()` method return?

A
The current position of the file cursor (in bytes).
B
The name of the file.
C
The size of the file.
D
The file's encoding.
22

Question 22

Analyze the code below. What is the correct way to strip the newline character from each line read?

python
with open('list.txt') as f:
    line = f.readline()
    clean_line = line.strip()
A
line.strip()
B
line.remove('\n')
C
line.delete_newline()
D
line - '\n'
23

Question 23

Can you use `with open(...)` to open multiple files at once?

python
with open('in.txt') as f1, open('out.txt', 'w') as f2:
    pass
A
Yes, this is valid syntax.
B
No, you must nest them.
C
No, `with` only supports one context manager.
D
Only in Python 4.0.
24

Question 24

What happens if you use `write()` on a file opened in `'a'` mode?

A
The data is added to the end of the file.
B
The file is cleared and then written to.
C
The data is written at the beginning, overwriting existing content.
D
It raises an error.
25

Question 25

Which exception is raised if you try to open a directory as a file?

A
IsADirectoryError
B
FileNotFoundError
C
PermissionError
D
ValueError
26

Question 26

Analyze the code below. What is the value of `f.closed` after the block?

python
with open('data.txt', 'w') as f:
    f.write('hi')
print(f.closed)
A
True
B
False
C
None
D
Error
27

Question 27

What is the purpose of the `buffering` argument in `open()`?

A
To control how data is buffered in memory before writing to disk.
B
To set the file size limit.
C
To encrypt the file.
D
To speed up internet downloads.
28

Question 28

Which method would you use to check if a file is readable?

A
readable()
B
can_read()
C
is_readable()
D
get_mode()
29

Question 29

Analyze the code below. What happens?

python
f = open('new.txt', 'w')
f.write(123)
A
TypeError: write() argument must be str, not int
B
It writes '123' to the file.
C
It writes the byte value 123.
D
It crashes the interpreter.
30

Question 30

What is the correct way to read a file line by line and stop when a specific line is found?

python
with open('log.txt') as f:
    for line in f:
        if 'ERROR' in line:
            print(line)
            break
A
This code is correct and efficient.
B
You must use while True and readline().
C
You must load the whole file first.
D
Break does not work in file loops.
31

Question 31

Which of the following is NOT a valid file mode?

A
'z'
B
'r'
C
'w'
D
'a'
32

Question 32

What happens if you open a file using `open('file.txt', 'w+')`?

A
The file is truncated (emptied) and opened for both reading and writing.
B
The file is opened for reading and writing without truncation.
C
It raises an error if the file exists.
D
It appends to the file.
33

Question 33

How can you check the name of the file associated with a file object `f`?

A
f.name
B
f.filename
C
f.path
D
f.get_name()
34

Question 34

Analyze the code below. What is the content of `data`?

python
with open('file.txt', 'r') as f:
    data = f.read(5)
A
The first 5 characters of the file.
B
The first 5 lines of the file.
C
The first 5 bytes (if binary mode).
D
The 5th character.
35

Question 35

What is the best way to handle file paths to ensure cross-platform compatibility?

A
Use the `os.path` module or `pathlib` library.
B
Always use forward slashes `/`.
C
Always use backslashes `\`.
D
Hardcode the paths.

QUIZZES IN Python