[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.
FeatureCode (a)Code (b)
Reads Entire File?YesNo, reads only first 100 characters
Returned ValueString containing entire file contentString 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:

  1. 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. The read() function, when called without any arguments, reads the entire file by default.
  2. 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. The read() function, when called with an argument (in this case, 100), reads only the specified number of characters from the file.

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:

Python
my_file = open('poem.txt', 'r')
content = my_file.read(100)
my_file.close()

Using with statement:

Python
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.

"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment