Python File
Handling
Introduction to File
Handling
File handling in Python allows reading from
and writing to files.
Key functions:
- open()
- read(), readline(), readlines()
- write(), writelines()
- close()
Opening Files
Syntax: open(filename, mode)
Modes:
- 'r': Read
- 'w': Write (overwrites file)
- 'a': Append
- 'b': Binary
- 'x': Create
- 'r+': Read and Write
Reading Files
- read(): Reads entire file
- readline(): Reads a single line
- readlines(): Reads all lines into a list
Writing Files
- write(): Writes string to file
- writelines(): Writes list of strings
Note: Always close the file using close() or use
with statement.
With Statement
Using 'with' automatically closes the file:
with open('file.txt', 'r') as f:
data = f.read()
No need to call close().
File Handling Modes
Text Mode vs Binary Mode:
- Text mode: Default, reads/writes string data
- Binary mode: For non-text files (images, etc.)
Use 'rb', 'wb', 'ab' for binary
1. Which method is used to read the entire file
content?
A. read()
B. readline()
C. readlines()
D. write()
Answer:
A
2. What does the 'w' mode
do?
A. Reads a file
B. Appends to a file
C. Writes and overwrites file
D. Reads and writes
Answer:
C
3. What happens if you open a non-existing
file in 'r' mode?
A. File is created
B. File is deleted
C. Error is raised
D. File is opened as empty
Answer:
C
4. Which function is used to write a list of
strings to a file?
A. write()
B. writeline()
C. writelines()
D. writer()
Answer:
C
5. What is the advantage of using 'with'
statement?
A. Automatically opens file
B. Avoids using variables
C. No need to close the file
manually
D. Writes faster
Answer:
C
6. Which mode opens a file for both reading
and writing?
A. r
B. w
C. r+
D. a+
Answer:
C
7. What does 'rb' mode stand
for?
A. Read Binary
B. Read Both
C. Run Binary
D. None of the above
Answer:
A
8. What will open('file.txt', 'a')
do?
A. Overwrite the file
B. Append to the file
C. Delete file
D. Read file
Answer:
B
9. Which function reads one line at a
time?
A. read()
B. readline()
C. readlines()
D. line()
Answer:
B
10. Which of these is not a valid file
mode?
A. x
B. a
C. m
D. r+
Answer:
C