Python File Handling Practice Questions – Test 3
1. What is the difference between r+ and w+ mode?
2. What is the difference between write and append mode?
3. Which method is used to close the file in python?
4. Write the statement to close the file “test.txt” which is associated with file
object named “fo”.
5. Write one similarity and one difference between a+ and w+.
6. What is the difference between read() and read(n) functions?
7. What is the difference between readline() and readlines()?
8. Write a program to read first 10 characters from a file named “data.txt”
9. Write a program to read entire content from the file named “test.txt”
10. Write the output of the following, if the data stored in file “try.txt” is given
below. (“f” is the file object associated with file)
Try Try but never cry
print(f.read(4))
print(f.read(5))
print(f.read())
ANSWER KEY
1. Ans. r+ mode will return error if file does not exist while w+ mode will create a new
file if file does not exist.
2. Write mode over writes the existing data while append mode add the new data at the
end of the file.
3. Ans. close()
4. Ans. fo.close()
5. NO (ANS)
6. Ans. read() : will read entire data from the file.
read(n) : will read first n characters/bytes from the file.
7. Ans. readline() :This function will read one line from the file.
readlines() : This function will read all the lines from the files.
8. Ans.
f = open(“data.txt”,”r”)
data = f.read(10)
print(data)
9. Ans.
f = open(“test.txt, “r”)
d = f.read()
print(d)
10. ANS. Try
Try b
ut never cry