[Type B] File Handling – Chapter 5 Sumita Arora
Type B: Application Based Questions
Table of Contents
1. How are following codes different from one another?
(a)my_file = open('poem.txt', 'r')
my_file.read()
(b)my_file = open('poem.txt', 'r')
my_file.read(100)
Answer: These codes differ in the amount of data they read from the file:
- Code (a) reads the entire file.
- Code (b) reads only the first 100 characters.
Feature | Code (a) | Code (b) |
---|---|---|
Reads Entire File? | Yes | No, reads only first 100 characters |
Returned Value | String containing entire file content | String containing first 100 characters |
Explanation:
Both code snippets (a) and (b) open a file called ‘poem.txt’ in read mode (‘r’). However, they differ in how they read the file’s content:
- my_file.read()
- This code snippet reads the entire content of the file ‘poem.txt’ into a string and assigns it to the variable
my_file
. Theread()
function, when called without any arguments, reads the entire file by default.
- This code snippet reads the entire content of the file ‘poem.txt’ into a string and assigns it to the variable
- my_file.read(100)
- This code snippet reads the first 100 characters of the file ‘poem.txt’ into a string and assigns it to the variable
my_file
. Theread()
function, when called with an argument (in this case, 100), reads only the specified number of characters from the file.
- This code snippet reads the first 100 characters of the file ‘poem.txt’ into a string and assigns it to the variable
When working with files, it’s essential to close them after you’re done using them. Failing to do so might result in resource leaks and unexpected behavior. You can either use the close()
method or the with
statement to ensure proper closure. Here are the examples using both methods:
Using close()
method:
my_file = open('poem.txt', 'r')
content = my_file.read(100)
my_file.close()
Using with
statement:
with open('poem.txt', 'r') as my_file:
content = my_file.read(100)
# No need to call `close()` as it's automatically handled by the `with` statement
Best practice: Use the with
statement to ensure that the file is properly closed after use.
Good work posting these questions in detail!